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 type erasure in Java generics?
Answer: The compiler removes all generic type information at runtime
Type erasure means the compiler replaces generic type parameters with their bounds (or Object) in bytecode, so type info is unavailable at runtime.
Which of the following is a valid generic method declaration?
Answer: public T swap(T a, T b) {}
A generic method must declare its type parameter inside angle brackets before the return type, as in ` T swap(T a, T b)`.
What is the output of the following code? ```java Deque dq = new ArrayDeque<>(); dq.push(1); dq.push(2); dq.push(3); System.out.println(dq.poll()); ```
Answer: 3
push() adds to the front (stack behavior), so after pushing 1, 2, 3 the front is 3; poll() retrieves from the front, returning 3.
Which statement correctly describes the difference between HashSet and LinkedHashSet?
Answer: LinkedHashSet maintains insertion order; HashSet does not
LinkedHashSet maintains insertion order by using a doubly-linked list alongside the hash table, while HashSet provides no order guarantee.
What does the following code print? ```java PriorityQueue pq = new PriorityQueue<>(); pq.offer(5); pq.offer(1); pq.offer(3); System.out.println(pq.poll()); ```
Answer: 1
PriorityQueue is a min-heap by default, so poll() always retrieves the smallest element, which is 1.
Which wildcard allows reading elements from a generic collection without writing to it?
Answer: List
An upper-bounded wildcard `? extends T` permits reading as T but prevents adding elements (except null), enforcing producer semantics.
What exception is thrown when a ConcurrentModificationException occurs?
Answer: It is thrown when a collection is modified while iterating over it with a fail-fast iterator
Fail-fast iterators (like those of ArrayList) throw ConcurrentModificationException if the collection is structurally modified during iteration outside of the iterator itself.