Generics and Collections Flashcards
7 cards from real OCP practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Generics and Collections flashcards as text
What is the correct way to create an unmodifiable Map with three entries in Java 9+?
Answer: Map.of("a",1,"b",2,"c",3)
Map.of() (introduced in Java 9) creates an immutable map with up to 10 key-value pairs specified inline without helper classes.
Which statement correctly describes how HashMap handles hash collisions in Java 8+?
Answer: It chains colliding entries in a linked list, switching to a red-black tree when the bin reaches 8 entries
Java 8+ HashMap uses chaining (linked list per bucket) and converts a bucket to a balanced tree when it exceeds a threshold of 8 entries, improving worst-case lookup from O(n) to O(log n).
What happens if two different keys have the same hashCode() but are not equal() in a HashMap?
Answer: Both entries are stored in the same bucket using a linked structure
HashMap allows multiple keys in the same bucket; equality (via equals()) is used to differentiate them, so both entries coexist in the bucket chain.
Which utility method sorts a List in reverse natural order in Java 8+?
Answer: Collections.sort(list, Comparator.reverseOrder())
Collections.sort(list, Comparator.reverseOrder()) sorts the list in descending natural order using the built-in reversed comparator.
What is the result of adding a duplicate element to a HashSet?
Answer: The add() method returns false and the set remains unchanged
Set.add() returns false without modifying the set when the element already exists (as determined by equals() and hashCode()).
Which of the following correctly declares a bounded generic class that only accepts Number subclasses?
Answer: class Box {}
An upper-bounded type parameter on a class uses ``, restricting T to Number itself or any subclass like Integer or Double.
What does List.copyOf(originalList) guarantee in Java 10+?
Answer: An unmodifiable list containing the same elements in the same order
List.copyOf() returns an unmodifiable List containing the elements of the given collection in encounter order; mutations to the original do not affect the copy.