SCJP Java Collections Framework 1 — Questions and Answers
Question 1: Which Java collection class allows duplicate elements and maintains insertion order?
- HashSet
- TreeSet
- ArrayList (Correct answer)
- LinkedHashSet
Correct answer: ArrayList
`ArrayList` is an ordered, index-based list that allows duplicate elements and preserves insertion order.
Question 2: Which interface does HashMap implement?
- List
- Set
- Map (Correct answer)
- Queue
Correct answer: Map
`HashMap` implements the `Map` interface, storing key-value pairs where keys must be unique.
Question 3: What is the time complexity of retrieving an element from a HashMap by key (average case)?
- O(n)
- O(log n)
- O(1) (Correct answer)
- O(n log n)
Correct answer: O(1)
HashMap provides O(1) average-case performance for `get()` and `put()` due to hashing.
Question 4: Which collection maintains elements in a sorted natural order and does not allow duplicates?
- ArrayList
- LinkedList
- TreeSet (Correct answer)
- ArrayDeque
Correct answer: TreeSet
`TreeSet` is a sorted Set implementation that stores unique elements in their natural order or by a Comparator.
Question 5: What happens when you add a duplicate key to a HashMap?
- An exception is thrown
- The old value is retained and the new one is discarded
- The old value is replaced by the new value (Correct answer)
- Both values are stored under the same key
Correct answer: The old value is replaced by the new value
When a duplicate key is inserted into a HashMap, the existing value associated with that key is overwritten.
Question 6: Which of the following is NOT part of the Java Collections Framework hierarchy?
- List
- Set
- Map
- Array (Correct answer)
Correct answer: Array
Arrays are native Java constructs and are not part of the Collections Framework; they do not implement Collection or Map.
Which Java collection class allows duplicate elements and maintains insertion order?