In Java 2024, if you need a collection that automatically removes entries based on garbage collection patterns, which would you choose?
AWeakHashMap
BIdentityHashMap
CEnumMap
DConcurrentHashMap
Correct Answer:
A. WeakHashMap
EXPLANATION
WeakHashMap uses weak references for keys. When a key is no longer referenced elsewhere, it becomes eligible for garbage collection and is automatically removed from the map.
Consider this code: List list = new CopyOnWriteArrayList(); list.add("A"); list.add("B"); Iterator itr = list.iterator(); list.add("C"); System.out.println(itr.next());
AThrows ConcurrentModificationException
BPrints 'A'
CPrints 'C'
DThrows NoSuchElementException
Correct Answer:
B. Prints 'A'
EXPLANATION
CopyOnWriteArrayList creates a snapshot for iterators, so modifications after iterator creation don't affect the iteration. Iterator sees only original elements: A and B.
In Java 2024-25, which enhancement improved record support in collections?
ARecords automatically implement Comparable
BRecords can be used as sealed collection types with pattern matching
CRecords eliminate the need for custom Comparators
DRecords are automatically thread-safe
Correct Answer:
B. Records can be used as sealed collection types with pattern matching
EXPLANATION
Java 21+ enhanced sealed classes and pattern matching, allowing records to be used with pattern matching in collection operations and switch statements for type-safe data handling.
Which of these operations is guaranteed to be atomic in ConcurrentHashMap?
Aif(!map.containsKey(key)) map.put(key, value);
Bmap.putIfAbsent(key, value);
Cmap.get(key) followed by map.put(key, newValue);
Dmap.remove(key) followed by map.put(key, value);
Correct Answer:
B. map.putIfAbsent(key, value);
EXPLANATION
putIfAbsent() is an atomic operation. Options A and C-D are compound operations that are not atomic and can have race conditions between checks and modifications.
What is the behavior of WeakHashMap when a key is no longer strongly referenced?
AThe entry remains in the map forever
BThe entry is eligible for garbage collection
CA NullPointerException is thrown
DThe key is automatically reset to null
Correct Answer:
B. The entry is eligible for garbage collection
EXPLANATION
WeakHashMap uses weak references for keys. When a key is no longer strongly referenced elsewhere, it becomes eligible for garbage collection, and its entry is removed from the map.
How does Java 8+ handle hash collisions in HashMap differently?
AUses double hashing
BConverts bucket linked list to Red-Black tree when size exceeds threshold
CIncreases hash table size automatically
DUses linear probing
Correct Answer:
B. Converts bucket linked list to Red-Black tree when size exceeds threshold
EXPLANATION
Java 8+ introduced tree nodes: when a bucket's linked list size exceeds TREEIFY_THRESHOLD (8), it converts to a Red-Black tree for better performance (O(log n) vs O(n)).