Collections interview questions
HashMap internals, ArrayList vs LinkedList, fail-fast iterators and the other collection questions interviewers ask most.
Collections questions are almost guaranteed in a Java interview, and "how does HashMap work?" is the most famous of all.
01Must-know answers
1. How does HashMap work internally?
An array of buckets (16 by default). put computes hashCode, spreads the bits, and picks a bucket with hash & (n - 1). An equal key (same hash and equals) gets its value replaced; otherwise a node is added. Collisions chain in a list, which becomes a red-black tree when a bucket has more than 8 nodes and the table has at least 64 buckets. When size exceeds capacity × 0.75, the table doubles. Average O(1). (7.5)
2. HashMap vs Hashtable vs ConcurrentHashMap?
HashMap: not thread-safe, allows one null key and null values. Hashtable: legacy, every method synchronised, no nulls. ConcurrentHashMap: thread-safe with lock-free reads and per-bucket write locking, atomic merge and compute, no nulls. (9.9)
3. HashMap vs LinkedHashMap vs TreeMap? No order guaranteed / insertion or access order / sorted keys. O(1), O(1), O(log n). (7.4)
4. ArrayList vs LinkedList? ArrayList: a resizable array with O(1) access, low memory and cache-friendly. LinkedList: a doubly linked list with O(n) access and O(1) at the ends. Default to ArrayList; use ArrayDeque for queues and stacks. (7.2)
5. HashSet vs TreeSet? Hash-based with O(1) and no order, vs a red-black tree with O(log n), sorted, and needing comparable elements or a Comparator. HashSet is backed by a HashMap. (7.3)
6. Comparable vs Comparator?
Comparable gives a class its natural order (compareTo); a Comparator is an external order, and you can have many. (7.7)
7. Fail-fast vs fail-safe iterators?
Fail-fast iterators (most java.util collections) throw ConcurrentModificationException when the collection is changed during iteration; fail-safe or weakly consistent ones (CopyOnWriteArrayList, ConcurrentHashMap) don't. (7.8)
8. How do you remove elements while iterating?
Iterator.remove() or removeIf, never list.remove inside a for-each. (7.2)
9. What's the difference between Collections.unmodifiableList and List.copyOf?
A read-only view of a live list, vs an immutable snapshot. (7.9)
10. Why does PriorityQueue iteration look unsorted?
It's a binary heap: only poll() returns elements in priority order. (7.6)
11. What's the time complexity of common operations?
| Collection | get / contains | add | remove |
|---|---|---|---|
| ArrayList | O(1) by index, O(n) by value | O(1) amortised at the end | O(n) |
| LinkedList | O(n) | O(1) at the ends | O(1) at the ends |
| HashMap, HashSet | O(1) average | O(1) average | O(1) average |
| TreeMap, TreeSet | O(log n) | O(log n) | O(log n) |
| PriorityQueue | O(1) peek | O(log n) | O(log n) poll |
| ArrayDeque | O(1) at the ends | O(1) at the ends | O(1) at the ends |
Loading the rest of the lesson…