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 result of compiling and running the following code? ```java List list = new ArrayList<>(); list.add("A"); List objList = list; objList.add(42); System.out.println(list.get(1)); ```
Answer: Compile error: incompatible types
A List cannot be assigned to List because generic types are invariant in Java, causing a compile-time error.
Which method signature correctly uses a lower-bounded wildcard to accept a List of Number or any supertype?
Answer: void process(List list)
The lower-bounded wildcard `? super Number` accepts List, List, or any list whose type is a supertype of Number.
What does the Collections.unmodifiableList() method return?
Answer: A view that throws UnsupportedOperationException on mutation
Collections.unmodifiableList() returns a view backed by the original list; structural modifications through the view throw UnsupportedOperationException.
Which statement about TreeMap is correct?
Answer: It maintains keys in natural sorted order
TreeMap stores keys in their natural ordering (or by a provided Comparator), unlike HashMap which uses hashing.
Given `Map> map`, which generic method call compiles without an unchecked warning?
Answer: map.put("k", Arrays.asList(1, 2, 3))
Arrays.asList(1, 2, 3) infers List from the declared map type, so no unchecked warning is generated.
What happens when you call Iterator.remove() before calling Iterator.next()?
Answer: It throws IllegalStateException
Iterator.remove() requires a prior call to next(); calling remove() without it throws IllegalStateException.
Which collection class is most appropriate for a LIFO (last-in, first-out) stack in modern Java?
Answer: java.util.ArrayDeque
ArrayDeque is recommended over the legacy Stack class for LIFO operations because it is faster and not synchronized.