Collections Quiz - Languages Java
Free practice quiz: Collections (Languages Java). 51 multiple-choice questions with answers and explanations. Play online, no sign-up needed.
Play all 51 questions freeSample questions
Which of the following is an immutable List implementation in Java's Collections framework?
- ArrayList
- LinkedList
- CopyOnWriteArrayList
- UnmodifiableList
Show answer
Answer: D. UnmodifiableList
UnmodifiableList is an interface that provides a view of a list that cannot be modified. While not a concrete class itself, implementations that wrap existing lists to make them unmodifiable (like `Collections.unmodifiableList(list)`) ensure immutability. ArrayList and LinkedList are mutable. CopyOnWriteArrayList provides thread-safe modification but is not immutable.
Which `Set` implementation does not permit duplicate elements and does not guarantee any specific order of elements?
- TreeSet
- LinkedHashSet
- HashSet
- EnumSet
Show answer
Answer: C. HashSet
`HashSet` uses a hash table for storage. It does not allow duplicate elements and does not maintain any order of iteration. `TreeSet` maintains sorted order, `LinkedHashSet` maintains insertion order.
Consider the code: `List<String> list = Arrays.asList("a", "b", "c"); Iterator<String> it = list.iterator(); it.next(); it.remove(); System.out.println(list);`. What will be printed?
- [a, b, c]
- [b, c]
- [a, c]
- An exception will be thrown.
Show answer
Answer: B. [b, c]
`Arrays.asList()` creates a fixed-size list backed by the array. The `iterator().remove()` method removes the element last returned by `next()`. So, after calling `it.next()`, "a" is the current element. Calling `it.remove()` removes "a" from the list. The list then contains ["b", "c"].
Which of the following is a `Map` interface implementation that uses a hash table and allows `null` keys and values?
- TreeMap
- Hashtable
- LinkedHashMap
- HashMap
Show answer
Answer: D. HashMap
`HashMap` uses a hash table and allows one `null` key and multiple `null` values. `TreeMap` does not allow `null` keys (but allows `null` values if the `Comparator` handles them). `Hashtable` does not allow `null` keys or values. `LinkedHashMap` also allows one `null` key and multiple `null` values.
What is the Big O notation for iterating through all elements of a `TreeSet` of size 'n'?
- O(1)
- O(log n)
- O(n)
- O(n log n)
Show answer
Answer: C. O(n)
Iterating through a `TreeSet` involves traversing the underlying balanced binary search tree. Since the tree contains 'n' elements, and visiting each element once takes constant time per node, the total time complexity for iteration is O(n).