Java Collections Framework: Detailed Breakdown
1. Core Interfaces
1.1 Iterable<T>
• Purpose: Root of the collections hierarchy for objects that can be iterated with
for-each.
• Key method: Iterator<T> iterator();
• Behavior: Enables for (T t : iterable) syntax. Most collection types
implement it.
Iterable<String> it = List.of("a", "b", "c");
for (String s : it) {
System.out.println(s);
1.2 Collection<E>
• Extends: Iterable<E>
• Purpose: General grouping of elements; base for List, Set, Queue.
• Core
methods: add, remove, contains, size, isEmpty, clear, iterator, addA
ll, removeAll, retainAll, toArray, containsAll, removeIf
• Fail-fast: Iterators typically detect structural modi cations
(throws ConcurrentModificationException).
1.3 List<E>
• Ordering: Maintains insertion order; allows positional access and duplicates.
• Extra methods: get, set, add(index,
element), remove(index), indexOf, lastIndexOf, listIterator, subL
ist, replaceAll, sort
1.4 Set<E>
• Uniqueness: No duplicates (based on equals()/hashCode() for hash-based,
natural/comparator order for sorted).
• Unordered (unless speci c implementation), no positional access.
• Common use-case: membership tests, de-duplication.
1.5 SortedSet<E> / NavigableSet<E>
fi
fi
• SortedSet: Maintains elements in ascending order.
• NavigableSet: Adds navigation
methods: lower, floor, ceiling, higher, pollFirst, pollLast.
1.6 Queue<E>
• FIFO semantics (typically).
• Core methods: offer, poll, peek, remove, element
1.7 Deque<E>
• Double-ended queue: insert/remove at both ends.
• Supports: stack (LIFO) via push/pop and queue operations.
• Extra: addFirst, addLast, removeFirst, removeLast, peekFirst, peekL
ast, push, pop
1.8 Map<K,V>
• Not a Collection, but core in the framework.
• Purpose: Key-value pairs. Unique keys.
• Core
methods: put, get, remove, containsKey, containsValue, keySet, valu
es, entrySet, putIfAbsent, computeIfAbsent, computeIfPresent, mer
ge, forEach
1.9 SortedMap<K,V> / NavigableMap<K,V>
• SortedMap: Keeps keys in sorted order.
• NavigableMap: Adds navigation methods (like lowerEntry, ceilingKey,
etc.).
2. List Implementations
2.1 ArrayList<E>
• Backing: Resizable array.
• Access: O(1) random access.
• Insert/remove: O(n) worst-case (shifting).
• Resize: Grows by ~1.5× when needed.
• Allows: null, duplicates.
List<String> al = new ArrayList<>();
al.add("apple");
al.add("banana");
al.add(1, "orange"); // insert at index
System.out.println(al.get(1)); // "orange"
al.remove("banana");
al.replaceAll(String::toUpperCase);
System.out.println(al); // [APPLE, ORANGE]
2.2 LinkedList<E>
• Structure: Doubly linked list.
• Implements: List, Deque.
• Access: O(n) random-access.
• Insert/remove: O(1) if you have iterator or at ends.
• Use-case: Queue/Deque or frequent insertions/deletions in middle.
Deque<Integer> dq = new LinkedList<>();
dq.addFirst(10);
dq.addLast(20);
System.out.println(dq.removeFirst()); // 10
2.3 Vector<E> (legacy)
• Thread-safe: All methods are synchronized.
• Resizable array like ArrayList but with overhead.
• Growth: Default doubling.
• Modern code prefers ArrayList + external synchronization if needed.
Vector<String> v = new Vector<>();
v.add("x");
v.add("y");
System.out.println(v.get(0)); // "x"
2.4 Stack<E> (legacy subclass of Vector)
• Extends: Vector
• LIFO behavior: push, pop, peek.
• Recommendation: Use ArrayDeque for stack instead.
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // 2
3. Deque / Queue Implementations
3.1 ArrayDeque<E>
• Resizable array acting as deque.
• Ef cient add/remove at both ends: O(1)
• No capacity restrictions (beyond memory).
• Not thread-safe.
• Preferred over LinkedList for stack/queue when thread-safety not needed.
Example (stack):
Deque<String> stack = new ArrayDeque<>();
stack.push("first");
stack.push("second");
System.out.println(stack.pop()); // "second"
Example (queue):
Queue<String> q = new ArrayDeque<>();
q.offer("a");
q.offer("b");
System.out.println(q.poll()); // "a"
fi
3.2 LinkedList (as Deque)
• Implements Deque so same operations possible (see above).
3.3 PriorityQueue<E>
• Ordering: Elements ordered by natural order or provided Comparator.
• Not FIFO; head is least element.
• Implementation: Binary heap.
• Nulls: Not allowed.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(1);
pq.offer(3);
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // 1,3,5
// Custom comparator:
PriorityQueue<String> pqStr = new
PriorityQueue<>(Comparator.comparingInt(String::length));
pqStr.offer("apple");
pqStr.offer("kiwi");
pqStr.offer("banana");
System.out.println(pqStr.poll()); // "kiwi" (shortest)
4. Set Implementations
4.1 HashSet<E>
• Backing: HashMap internally.
• Performance: O(1) average for add/remove/contains.
• Unordered.
• Null: One allowed.
Set<String> s = new HashSet<>();
s.add("a");
s.add("b");
s.add("a"); // duplicate ignored
System.out.println(s); // [a, b]
4.2 LinkedHashSet<E>
• Maintains insertion order using a linked list in addition to hash table.
• Same complexity as HashSet but with predictable iteration order.
Set<Integer> lhs = new LinkedHashSet<>();
lhs.add(3);
lhs.add(1);
lhs.add(2);
System.out.println(lhs); // [3, 1, 2]
4.3 TreeSet<E>
• Sorted set (implements NavigableSet).
• Backed by Red-Black Tree.
• Ordering: Natural or via Comparator.
• Operations: O(log n).
NavigableSet<String> ts = new TreeSet<>();
ts.add("banana");
ts.add("apple");
ts.add("cherry");
System.out.println(ts); // [apple, banana, cherry]
System.out.println(ts.lower("banana")); // "apple"
5. Map Implementations
5.1 HashMap<K,V>
• Backing: Hash table with buckets; since Java 8, buckets degrade to trees if
collisions high.
• Performance: O(1) average for get/put.
• Allows: one null key, multiple null values.
• Unordered.
Map<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.computeIfAbsent("cherry", k -> 30);
System.out.println(map.get("banana")); // 20
5.2 LinkedHashMap<K,V>
• Maintains insertion order (or access order if con gured).
• Useful for LRU caches.
Example (access-order LRU):
Map<Integer, String> lru = new LinkedHashMap<>(16, 0.75f, true);
lru.put(1, "one");
lru.put(2, "two");
lru.get(1); // updates access order
lru.put(3, "three");
System.out.println(lru.keySet()); // order reflects access
// Custom eldest removal:
int max = 2;
Map<Integer, String> cache = new LinkedHashMap<>(16, 0.75f,
true) {
protected boolean removeEldestEntry(Map.Entry<Integer,
String> eldest) {
return size() > max;
};
fi
5.3 Hashtable<K,V> (legacy)
• Synchronized counterpart to HashMap.
• No null keys or values.
• Legacy; prefer ConcurrentHashMap or external synchronization on modern
maps.
Hashtable<String, String> ht = new Hashtable<>();
ht.put("a", "alpha");
System.out.println(ht.get("a"));
5.4 TreeMap<K,V>
• Sorted map (implements NavigableMap).
• Keys sorted naturally or via a provided Comparator.
• Operations: O(log n).
NavigableMap<Integer, String> tm = new TreeMap<>();
tm.put(2, "two");
tm.put(1, "one");
tm.put(3, "three");
System.out.println(tm.firstKey()); // 1
System.out.println(tm.ceilingKey(2)); // 2
6. Best Practices, Pitfalls, and Performance Summary
Best Practices
• Prefer ArrayList over LinkedList unless you need frequent mid-list removals/
insertions and don’t need random access.
• Use ArrayDeque for stack/queue instead of legacy Stack or LinkedList when
thread-safety is not required.
• Override equals() and hashCode() correctly when using custom objects in
HashSet/HashMap.
• For predictable iteration order with hash-based collections, use
the Linked variants.
• For sorting or range queries, use TreeSet / TreeMap.
• Use computeIfAbsent, merge to reduce boilerplate when populating maps.
• Avoid modifying collections while iterating unless using the iterator’s remove().
Common Pitfalls
• Assuming HashMap is ordered.
• Using Vector / Hashtable in new code (legacy; better alternatives exist).
• Not synchronizing manually when iterating over synchronized wrappers
(e.g., Collections.synchronizedList) — need
external synchronized(...) block during iteration.
• Using mutable objects as keys without immutability guarantees, breaking map/
set behavior if their hashCode changes.
Performance Summary (Typical)
Acces Delet
Class/Interface Insert Notes
s e
ArrayList O(1) O(n) O(n) Dynamic array
*if at ends or via
LinkedList O(n) O(1)* O(1)*
iterator
O(1)
HashSet / HashMap O(1) O(1) Hash-based
avg
LinkedHashSet/ O(1)
O(1) O(1) Maintains order
LinkedHashMap avg
O(log O(log O(log Sorted (red-black
TreeSet / TreeMap
n) n) n) tree)
ArrayDeque O(1) O(1) O(1) Deque optimized
O(log O(log O(log
PriorityQueue Heap-based
n) n) n)
Composite Example: Word Frequency with Sorted Output
String text = "apple banana apple orange banana apple";
String[] words = text.split(" ");
Map<String, Integer> freq = new HashMap<>();
for (String w : words) {
freq.merge(w, 1, Integer::sum);
// Sort by frequency descending
List<Map.Entry<String, Integer>> sorted = new
ArrayList<>(freq.entrySet());
sorted.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
for (Map.Entry<String, Integer> entry : sorted) {
System.out.println(entry.getKey() + ": " +
entry.getValue());
Frequently Asked Interview Questions
General & Fundamentals
1. What is the Java Collections Framework?
A uni ed architecture for representing and manipulating collections of objects,
including interfaces (List, Set, Map), implementations (ArrayList, HashSet,
HashMap, etc.), and utility classes (Collections, Arrays).
2. What are the main interfaces in the Collections Framework?
Collection, List, Set, Queue, Deque, SortedSet, NavigableSet, Map, SortedMap,
NavigableMap, and Iterable.
3. What is the difference between Collection and Map?
Collection represents a group of individual elements (e.g., List, Set); Map
represents key-value pairs and is not a subtype of Collection.
4. What is Iterable?
Root interface that allows an object to be the target of the enhanced for-loop by
providing an iterator().
5. What is the difference between Iterator and ListIterator?
Iterator supports forward traversal and removal. ListIterator supports bidirectional
traversal, addition, modi cation, and index querying (only for lists).
6. What is fail-fast behavior?
Iterators detect structural modi cation (outside of iterator's own remove/add) and
throw ConcurrentModificationException.
fi
fi
fi
7. What is fail-safe?
Iterators that operate on a copy of the data (e.g., CopyOnWriteArrayList) and do
not throw ConcurrentModificationException on concurrent modi cation.
8. What is the difference between Comparable and Comparator?
Comparable de nes natural ordering via compareTo inside the class.
Comparator de nes external ordering via a separate object.
9. What method must you override when using custom objects as keys in
HashMap?
equals() and hashCode().
10. What is the contract between equals() and hashCode()?
If two objects are equal (equals() returns true), they must have the
same hashCode(). If hashCode() is same, equals() may still return false.
11. What is the default load factor of HashMap?
0.75.
12. What is initial capacity in HashMap?
Default is 16 buckets.
13. When does HashMap resize?
When number of entries exceeds capacity × loadFactor.
14. What is the complexity of get() and put() in HashMap?
Average O(1); worst-case O(log n) since Java 8 (due to treei cation).
15. What is treei cation in HashMap?
Buckets with many collisions convert from linked list to balanced tree (red-black
tree) for performance.
16. Can HashMap store null key or values?
Yes—one null key and multiple null values.
17. What is the difference between HashMap and Hashtable?
Hashtable is synchronized, doesn't allow null keys/values; HashMap is
unsynchronized and allows one null key.
fi
fi
fi
fi
fi
18. Why is ConcurrentHashMap preferred over synchronizing a HashMap?
It offers better concurrency using ner-grained locking or lock-free techniques
and avoids global lock bottleneck.
19. Which interfaces does ArrayList implement?
List, RandomAccess, Cloneable, Serializable.
20. What’s the difference between ArrayList and LinkedList?
ArrayList uses dynamic array—fast random access (O(1)); slow insert/remove in
middle (O(n)). LinkedList uses doubly-linked list—fast insertion/deletion if you
have node reference (O(1)), slow random access (O(n)).
21. What does RandomAccess marker interface indicate?
That the list supports fast (typically O(1)) random access. Implemented by
ArrayList.
22. How do you convert an array to a list?
Arrays.asList(array) ( xed-size view)
or new ArrayList<>(Arrays.asList(array)) for a resizable list.
23. How do you make a collection unmodi able?
Use Collections.unmodifiableList(...), unmodifiableSet(...),
etc.
24. What is a LinkedHashMap?
Hash-based map that maintains insertion order or access order.
25. How do you implement LRU cache using collections?
Use LinkedHashMap with access-order ag and override removeEldestEntry.
26. What’s the difference between Set and List?
Set disallows duplicates, no guaranteed order (unless speci c implementation).
List allows duplicates and maintains order.
27. What is the difference between HashSet and TreeSet?
HashSet is unordered, backed by hash table, O(1) operations. TreeSet is sorted
(natural or comparator), backed by red-black tree, O(log n) operations.
fi
fi
fl
fi
fi
28. What interface does TreeSet implement for navigation?
NavigableSet.
29. What is the difference between TreeSet and LinkedHashSet?
TreeSet sorts its elements; LinkedHashSet maintains insertion order.
30. How do you iterate over a map?
Through entrySet(), keySet(), or values();
best: for (Map.Entry<K,V> e : map.entrySet()).
31. What’s the difference between offer() and add() in queues?
add() throws exception on failure; offer() returns false.
32. What’s the difference between poll() and remove() in queues?
poll() returns null if empty; remove() throws exception.
33. What’s the difference between peek() and element()?
peek() returns null if empty; element() throws exception.
34. What is PriorityQueue and its ordering semantics?
Queue that orders elements according to natural ordering or provided
Comparator; head is least element.
35. Can PriorityQueue contain null?
No.
36. What’s the time complexity of add() and poll() in PriorityQueue?
O(log n).
37. What is Deque?
Double-ended queue supporting insertion/removal at both ends; can act as stack
or queue.
38. What are common implementations of Deque?
ArrayDeque, LinkedList.
39. Why prefer ArrayDeque over Stack?
ArrayDeque is more ef cient and has no legacy synchronization; Stack is legacy
and extends Vector.
40. How to get a thread-safe List?
Collections.synchronizedList(new ArrayList<>()) or use
concurrent classes like CopyOnWriteArrayList.
41. What is CopyOnWriteArrayList?
Thread-safe list where mutative operations copy the entire underlying array—
good for many reads, few writes.
42. What are the drawbacks of CopyOnWriteArrayList?
High overhead on write (copies entire array), not suitable for frequent mutations.
43. What is the difference between HashSet and LinkedHashSet?
LinkedHashSet maintains insertion order; HashSet does not.
44. How do you sort a List?
Collections.sort(list) or list.sort(Comparator).
45. What is the return type of Map.entrySet()?
Set<Map.Entry<K,V>>.
46. What is a NavigableMap?
Map with navigation methods like lowerEntry, ceilingKey, etc.; e.g.,
TreeMap.
47. What is the difference between HashMap and LinkedHashMap when
iterating?
LinkedHashMap retains predictable order; HashMap does not guarantee iteration
order.
48. How do you safely iterate over a synchronized collection?
Wrap iteration in synchronized block: synchronized(list) { for
(...) }.
fi
49. What is Collections.unmodi ableList()?
Returns an unmodi able view; underlying list changes re ect unless original
mutated.
50. What’s Collections.checkedList()?
Runtime type-safe wrapper that throws ClassCastException if wrong type added.
Intermediate / Implementation Details
51. What is rehashing?
Resizing and redistributing entries (e.g., in HashMap) when threshold exceeded.
52. What factor determines when a HashMap resizes?
Load factor × current capacity.
53. What is the purpose of transient in collection implementation?
Avoid serialization of internal elds; used internally for performance and
backward compatibility.
54. What’s the difference between remove() of iterator and
Collection.remove()?
Iterator’s remove() safely removes current element during iteration;
Collection.remove() may cause ConcurrentModi cationException.
55. How to get a sublist view?
list.subList(fromIndex, toIndex) (backed by original list).
56. What happens if you modify the underlying list of a subList directly?
Sublist re ects changes; structural modi cations outside sublist operations may
throw ConcurrentModi cationException.
57. What is the difference between putIfAbsent() and computeIfAbsent()?
putIfAbsent inserts if no mapping exists. computeIfAbsent computes value
via function if key absent.
fl
fi
fi
fi
fi
fi
fi
fl
58. What does merge() do in maps?
Combines existing value and new value using a remapping function if key exists,
otherwise inserts new value.
59. How does Collections.sort() work internally?
Dual-pivot quicksort for primitives; TimSort (hybrid stable) for objects since Java
7+.
60. What is the difference between contains() in List vs Set?
Set usually O(1) (hash-based), List O(n) linear scan.
61. What does entrySet().removeIf(...) do?
Removes map entries matching predicate in bulk.
62. Can you have duplicate keys in a Map?
No; putting same key replaces previous value.
63. Can you have duplicate values in a Map?
Yes; values can repeat.
64. How to iterate backward in a list?
Use ListIterator and hasPrevious()/previous().
65. What is EnumSet?
Highly ef cient set for enum types, internally bit-vector based.
66. What is EnumMap?
Map specialized for enum keys, very ef cient (array-backed).
67. Is TreeMap synchronized?
No; use Collections.synchronizedSortedMap(...) if needed.
68. What does Collections.reverseOrder() return?
A comparator that reverses natural ordering.
69. What’s the difference between size() and length?
size() is for collections; length is array property.
fi
fi
70. What is the bene t of using Map.compute()?
Update mapping in atomic, concise way based on existing value.
71. What interface does PriorityQueue implement?
Queue.
72. Does HashSet guarantee order?
No.
73. What does containsKey() use internally for HashMap?
Hashing the key and equals comparison in bucket.
74. How do you get values from a map as a collection?
map.values().
75. What is the time complexity to check if a HashSet contains an element?
O(1) average.
76. Why is HashMap iteration order unpredictable?
Buckets depend on hash codes and internal structure; not guaranteed.
77. How do you reverse a list?
Collections.reverse(list).
78. Can you make a deep copy of a collection?
Not automatically; you must clone each element if necessary (manual or via
serialization).
79. What is the difference between ArrayList’s ensureCapacity() and normal
add?
ensureCapacity pre-allocates space to avoid repeated resizing; add may
trigger resize.
80. What’s Collections.frequency()?
Returns number of occurrences of an element in a collection.
fi
Advanced / Behavioral / Edge Cases
81. What is the concurrency behavior of HashMap in multithreading without
external synchronization?
Not thread-safe; can lead to data corruption, in nite loops, or lost updates.
82. What is ConcurrentModi cationException?
Thrown when a collection is structurally modi ed while iterating outside of the
iterator’s own methods.
83. How to avoid ConcurrentModi cationException when removing during
iteration?
Use iterator’s remove() or collect to remove after loop, or use concurrent
collections.
84. What’s the difference between ConcurrentHashMap and
Collections.synchronizedMap()?
ConcurrentHashMap provides better concurrency (segment/lock striping or
internal updates) without locking entire map. synchronizedMap locks whole map
on each access.
85. What is a “backed collection”?
A collection view whose changes re ect on the original (e.g., subList or
Arrays.asList).
86. How does LinkedHashSet maintain order?
Maintains a doubly-linked list of entries in insertion order.
87. What is the difference between remove(Object) and removeIf(Predicate)?
remove(Object) removes a single matching element; removeIf removes all
elements satisfying the predicate.
88. How to create immutable collections in Java 9+?
Use factory methods like List.of(...), Set.of(...), Map.of(...).
89. What does Collections.emptyList() return?
Immutable empty list (singleton).
fi
fi
fl
fi
fi
90. Are the collections returned by List.of(...) modi able?
No; they are immutable.
91. How does TreeMap order keys by default?
Natural ordering of keys (via Comparable), unless a custom Comparator is
provided.
92. Can you use a mutable object as a key in a HashMap?
Risky; if its state (used in hashCode/equals) changes, lookup breaks.
93. What is the purpose of Collections.swap()?
Swaps two elements in a list by indices.
94. How can you get a synchronized Set?
Collections.synchronizedSet(new HashSet<>()).
95. What is the difference between put() and putIfAbsent()?
put() replaces existing value unconditionally; putIfAbsent() only sets if no
mapping exists.
96. What does retainAll() do?
Keeps only elements present in the speci ed collection (intersection).
97. What does removeAll() do?
Removes elements present in the speci ed collection (difference).
98. What is the behavior of subList() when you modify the backing list?
The sublist re ects change; some structural changes may cause
ConcurrentModi cationException.
99. What method gives you the index of an element in a list?
indexOf(Object).
100. What is Collections.unmodi ableMap()?
Returns an unmodi able view of a map.
101. Can TreeSet contain heterogeneous types?
No, unless comparator can handle them; otherwise ClassCastException.
fl
fi
fi
fi
fi
fi
fi
102. What is difference between HashMap.keySet() and Map.entrySet()?
keySet() gives set of keys; entrySet() gives key-value pairs enabling
access to both and more ef cient bulk operations.
103. Is LinkedList better than ArrayList for queue implementation?
No; ArrayDeque is preferred. LinkedList can be used but has more overhead.
104. How to remove duplicates from a list?
new ArrayList<>(new LinkedHashSet<>(list)) for preserving order.
105. What’s the difference between List’s addAll() and repeated add()?
addAll() can leverage bulk optimizations; repeated add() is per-element.
106. What does Collections.disjoint(Collection a, Collection b) do?
Returns true if the two collections have no elements in common.
107. What is the purpose of Collections.unmodi ableCollection()?
Returns a read-only view to prevent modi cation.
108. What’s the difference between toArray() and toArray(T[] a)?
No-arg version returns Object[]; typed version returns array of provided runtime
type.
109. Why would you use TreeMap over HashMap?
Need sorted keys or range views.
110. What are navigable methods in NavigableMap?
lowerEntry, floorEntry, ceilingEntry, higherEntry, pollFirstEntr
y, etc.
111. What is a “view” in the context of collections?
A collection backed by another (e.g., keySet() or subList), re ecting changes.
112. How to get the descending order of a TreeSet?
Use descendingSet().
fi
fi
fi
fl
113. What’s the difference between HashSet and CopyOnWriteArraySet?
HashSet is not thread-safe; CopyOnWriteArraySet is thread-safe via copy-on-
write.
114. What is LinkedHashMap’s access-order mode used for?
Implementing LRU caches.
115. What happens if you modify a HashMap while iterating using its iterator?
ConcurrentModi cationException.
116. Can you iterate over a ConcurrentHashMap while modifying it?
Yes; iterators are weakly consistent (won’t throw CME and re ect some but not
necessarily all changes).
117. What is the difference between poll() and peek() in a queue?
poll() removes head; peek() only retrieves without removing.
118. What’s the behavior of Collections. ll()?
Replaces all elements in a list with the speci ed element.
119. What’s Collections.copy()?
Copies elements from source list to destination list; destination must be at least
as large.
120. Can you use Collections.sort() on an unmodi able list?
No; it will throw UnsupportedOperationException.
Speci c Trick / Scenario Questions
121. How to implement a frequency counter using collections?
Use Map<T, Integer> and merge(key, 1, Integer::sum).
122. How to get top N frequent elements?
Build frequency Map, then sort entries by value or use a PriorityQueue (min-heap
of size N).
fi
fi
fi
fi
fi
fl
123. How to reverse a LinkedList?
Manual pointer manipulation or using Collections.reverse(List) if
converted to list.
124. How to convert a Map to list of entries sorted by value?
map.entrySet().stream().sorted(Map.Entry.comparingByValue()
).collect(...).
125. How to safely remove entries from a map while iterating?
Use Iterator over entrySet() and call iterator.remove() or use removeIf on
entry set.
126. What is the effect of Collections.unmodi ableList(original) when you
modify original?
Unmodi able view re ects changes in original.
127. How to implement a thread-safe LRU cache?
Collections.synchronizedMap(new LinkedHashMap<>(..., true)
{ removeEldestEntry(...) }) or use ConcurrentLinkedHashMap (third-
party).
128. How do you randomize elements in a list?
Collections.shuffle(list).
129. Difference between ArrayList and Vector?
Vector is synchronized (legacy), ArrayList is unsynchronized and faster in single-
threaded contexts.
130. What is the signi cance of modCount in collections?
Tracks structural modi cations for fail-fast behavior.
131. How do you get a synchronized Map?
Collections.synchronizedMap(new HashMap<>()).
132. Can you use null in a TreeMap?
Only if a comparator allows it or key is comparable and not null; raw TreeMap
with natural ordering does not allow null key.
fi
fi
fl
fi
fi
133. What method would you use to get a descending map from a TreeMap?
descendingMap().
134. What’s the difference between HashSet.contains() and List.contains() in
performance?
HashSet average O(1); List O(n).
135. How to check if two collections have any common elements?
Collections.disjoint(a, b) returns true if no intersection.
136. What is the difference between Set.of(...) and new HashSet<>(...)?
Set.of returns immutable set and disallows null; HashSet is mutable and allows
null.
137. Can you use primitive types in collections directly?
No; use wrapper classes (autoboxing handles most conversions).
138. What is a “weak reference” map?
WeakHashMap uses weak keys; entries removed when key no longer strongly
referenced.
139. What’s IdentityHashMap?
Uses reference equality (==) instead of equals() for keys.
140. What is the difference between keySet() and values() in Map?
keySet() returns set of keys; values() returns collection of values.
141. How do you safely convert a Map to a List of keys?
new ArrayList<>(map.keySet()).
142. What’s the difference between List.of() and Arrays.asList()?
List.of() returns immutable list; Arrays.asList() returns xed-size view
(backed by array) that allows nulls.
143. What is the internal default growth policy of ArrayList?
New capacity = old + (old >> 1) (approx 1.5×).
fi
144. What happens if you call next() when hasNext() is false on iterator?
Throws NoSuchElementException.
145. What is a Spliterator?
Splittable iterator designed for parallelism, used by streams.
146. What interface do both HashMap and TreeMap implement?
Map.
147. How to get the rst and last element of a TreeSet?
first() and last() methods.
148. What is the difference between pollFirst() and removeFirst() in Deque?
pollFirst() returns null if empty; removeFirst() throws exception.
149. What’s the difference between offerLast() and addLast()?
offerLast() returns false if capacity-limited and fails; addLast() may throw
exception.
150. When would you use Vector today?
Generally not—use ArrayList or concurrent collections. Vector is legacy; only if
maintaining legacy code.
fi