SCJP Java Collections Framework 2 — Questions and Answers
Question 1: Which method must be overridden in a class for its objects to work correctly as HashMap keys?
- toString() and clone()
- equals() and hashCode() (Correct answer)
- compareTo() and compare()
- finalize() and wait()
Correct answer: equals() and hashCode()
HashMap uses `hashCode()` to find the bucket and `equals()` to confirm key equality, so both must be correctly overridden.
Question 2: Which List implementation provides O(1) add/remove at the ends but O(n) for random access?
- ArrayList
- Vector
- LinkedList (Correct answer)
- Stack
Correct answer: LinkedList
`LinkedList` uses a doubly-linked list, giving O(1) insertions at head/tail but O(n) for index-based access.
Question 3: What is the difference between `Iterator` and `ListIterator` in Java?
- ListIterator can traverse in both directions; Iterator is forward-only (Correct answer)
- Iterator is for Maps; ListIterator is for Lists
- ListIterator cannot remove elements; Iterator can
- They are identical
Correct answer: ListIterator can traverse in both directions; Iterator is forward-only
`ListIterator` extends `Iterator` with the ability to traverse a list in both forward and backward directions and also supports `add()` and `set()`.
Question 4: Which collection class is synchronized and considered the thread-safe version of ArrayList?
- LinkedList
- TreeList
- Vector (Correct answer)
- ArrayDeque
Correct answer: Vector
`Vector` is a synchronized, thread-safe dynamic array, essentially the legacy thread-safe counterpart to `ArrayList`.
Question 5: What does the `Collections.sort()` method require from the objects it sorts?
- Objects must implement Serializable
- Objects must implement Comparable (Correct answer)
- Objects must be primitives
- Objects must override toString()
Correct answer: Objects must implement Comparable
`Collections.sort()` requires list elements to implement `Comparable` so their natural ordering can be used.
Question 6: Which Map implementation maintains keys in their insertion order?
- HashMap
- TreeMap
- LinkedHashMap (Correct answer)
- Hashtable
Correct answer: LinkedHashMap
`LinkedHashMap` extends `HashMap` and maintains a linked list of entries in insertion order.
Which method must be overridden in a class for its objects to work correctly as HashMap keys?