1Z0-819 Collections Framework 4 — Questions and Answers
Question 1: What is the behavior of `TreeMap.subMap(fromKey, toKey)` with respect to the boundary keys?
- Inclusive on both ends
- Exclusive on both ends
- Inclusive on fromKey, exclusive on toKey (Correct answer)
- Exclusive on fromKey, inclusive on toKey
Correct answer: Inclusive on fromKey, exclusive on toKey
`TreeMap.subMap(fromKey, toKey)` returns a view with `fromKey` inclusive and `toKey` exclusive, matching the convention of standard range methods.
Question 2: Which class provides a thread-safe variant of `HashMap` without synchronizing the entire map?
- Hashtable
- SynchronizedMap
- ConcurrentHashMap (Correct answer)
- Collections.synchronizedMap()
Correct answer: ConcurrentHashMap
`ConcurrentHashMap` uses segment-level or bucket-level locking to allow concurrent reads and partial concurrent writes without locking the full map.
Question 3: Which `Map` method was added in Java 8 and computes a new value only if the key is absent?
- getOrDefault()
- putIfAbsent()
- computeIfAbsent() (Correct answer)
- merge()
Correct answer: computeIfAbsent()
`computeIfAbsent(key, mappingFunction)` invokes the function to compute a value only when the key is not already present, and stores the result.
Question 4: What exception is thrown when you attempt to add a null element to a `TreeSet`?
- IllegalArgumentException
- UnsupportedOperationException
- NullPointerException (Correct answer)
- ClassCastException
Correct answer: NullPointerException
`TreeSet` uses natural ordering or a `Comparator`, and comparing `null` causes a `NullPointerException` when the first comparison is attempted.
Question 5: Which of the following collection factory methods allows duplicate elements?
- Set.of(1, 1)
- Map.of("a", 1, "a", 2)
- List.of(1, 1) (Correct answer)
- Both Set.of and Map.of allow duplicates
Correct answer: List.of(1, 1)
`List.of()` permits duplicate elements, whereas `Set.of()` and `Map.of()` with duplicate keys/elements throw `IllegalArgumentException` at construction time.
Question 6: When using `Collections.sort(List<T> list)`, what must type `T` satisfy?
- T must extend Comparator
- T must implement Comparable (Correct answer)
- T must be Serializable
- T must be a Number subtype
Correct answer: T must implement Comparable
`Collections.sort()` requires elements to implement `Comparable<T>` so their natural ordering can be used; otherwise, a `ClassCastException` is thrown at runtime.
Question 7: Which `Queue` method adds an element and throws an exception if capacity is exceeded, rather than returning false?
- offer()
- add() (Correct answer)
- put()
- enqueue()
Correct answer: add()
`add()` throws `IllegalStateException` when the queue is full, while `offer()` returns `false` on failure and is preferred for capacity-constrained queues.
What is the behavior of `TreeMap.subMap(fromKey, toKey)` with respect to the boundary keys?