Interview
Collections Framework — Interview Questions (120+)
Detailed Questions
1. Overview of the Collections hierarchy?
- Short:
Iterable→Collection→ List/Set/Queue;Mapis separate. - Detailed:
Collectiondefines add/remove/contains.List(ordered, indexed, duplicates),Set(unique),Queue/Deque(FIFO/LIFO).Map(key→value) is not aCollection. Implementations:ArrayList,LinkedList,HashSet,TreeSet,HashMap,TreeMap,ArrayDeque,PriorityQueue. - Example:
List<Integer> l = new ArrayList<>();
2. ArrayList vs LinkedList?
- Short: ArrayList = array (fast random access); LinkedList = nodes (fast head/tail ops).
- Detailed: ArrayList: O(1) get, O(n) middle insert/remove, cache-friendly, amortized O(1) append. LinkedList: O(1) add/remove at ends, O(n) get, more memory per node. In practice ArrayList wins for most workloads.
- Example: Use
ArrayDequeover LinkedList for stack/queue.
3. How does HashMap work internally?
- Short: Array of buckets; index from hash; chaining; treeify on heavy collisions.
- Detailed: Key's
hashCodeis spread (h ^ (h>>>16)) and masked to a bucket. Collisions form a linked list; since Java 8, a bucket with >8 entries (and table ≥64) becomes a red-black tree (O(log n)). Resizes when size > capacity×loadFactor (0.75), doubling capacity and rehashing. - Example: Poor
hashCode→ all in one bucket → O(n) lookups.
4. HashMap vs Hashtable vs ConcurrentHashMap?
- Short: HashMap (not synced, allows null), Hashtable (legacy, fully synced), ConcurrentHashMap (scalable concurrency).
- Detailed: Hashtable locks the whole map (slow). ConcurrentHashMap uses bucket-level locking/CAS, no null keys/values, scales with cores. HashMap allows one null key and null values but isn't thread-safe.
- Example: Shared cache →
ConcurrentHashMap.
5. HashSet vs TreeSet vs LinkedHashSet?
- Short: Hash=unordered O(1); Tree=sorted O(log n); Linked=insertion order.
- Detailed: HashSet backed by HashMap. TreeSet backed by red-black tree (needs Comparable/Comparator), supports range ops (
headSet,floor). LinkedHashSet preserves insertion order. - Example: Need sorted unique → TreeSet.
6. HashMap vs TreeMap vs LinkedHashMap?
- Short: Same trade-offs as the Set variants.
- Detailed: TreeMap keeps keys sorted (NavigableMap:
firstKey,ceilingKey,subMap). LinkedHashMap can be access-ordered (great for LRU caches viaremoveEldestEntry). - Example: LRU cache →
LinkedHashMap(accessOrder=true).
7. How to make a collection thread-safe?
- Short: Use concurrent collections or
Collections.synchronizedX. - Detailed: Prefer
ConcurrentHashMap,CopyOnWriteArrayList,BlockingQueue.Collections.synchronizedListwraps with a single lock (still need manual sync when iterating). - Example:
List<T> s = Collections.synchronizedList(new ArrayList<>());
8. fail-fast vs fail-safe iterators?
- Short: fail-fast throws CME on concurrent modification; fail-safe iterates a snapshot.
- Detailed: ArrayList/HashMap iterators are fail-fast (modCount check). CopyOnWriteArrayList and ConcurrentHashMap are fail-safe (weakly consistent).
- Example: Remove during loop with
Iterator.remove()to avoid CME.
9. What is the load factor and capacity?
- Short: Capacity = bucket count; load factor = fill threshold (0.75).
- Detailed: Higher load factor saves memory but increases collisions; lower reduces collisions but wastes space. Size init capacity to avoid rehashing if you know the size.
- Example:
new HashMap<>(expected/0.75 + 1).
10. Why must map keys be immutable / have stable hashCode?
- Short: Changing a key's hash after insertion makes it unfindable.
- Detailed: The entry sits in a bucket based on the original hash; mutating fields used by hashCode/equals breaks lookups.
- Example: Don't use a mutable object whose fields change as a HashMap key.
11. Comparable vs Comparator (collections context)?
- Short: Natural ordering vs custom/multiple orderings.
- Detailed: TreeSet/TreeMap and
Collections.sortuse Comparable by default; pass a Comparator to override. Compose withcomparing,thenComparing,reversed,nullsFirst. - Example:
list.sort(Comparator.comparingInt(String::length));
12. How does ConcurrentHashMap achieve concurrency?
- Short: Bucket-level CAS + synchronized bins; no global lock.
- Detailed: Java 8+ uses per-bin synchronization and CAS for updates; reads are mostly lock-free.
compute,merge,computeIfAbsentare atomic per key. - Example:
map.merge(key, 1, Integer::sum)for atomic counters.
13. What is CopyOnWriteArrayList good for?
- Short: Read-heavy, rarely-written shared lists.
- Detailed: Every write copies the array; iterators see an immutable snapshot (no CME). Expensive writes, cheap concurrent reads.
- Example: Listener lists.
14. What are BlockingQueues?
- Short: Thread-safe queues that block on full/empty.
- Detailed:
ArrayBlockingQueue(bounded),LinkedBlockingQueue,PriorityBlockingQueue,SynchronousQueue,DelayQueue. Core to producer/consumer and thread pools. - Example:
queue.put(x)blocks if full;queue.take()blocks if empty.
15. How to remove elements safely while iterating?
- Short: Use
Iterator.remove()orremoveIf. - Detailed: Structural modification through the collection during a for-each causes CME.
removeIf(predicate)is concise and safe. - Example:
list.removeIf(x -> x % 2 == 0);
Rapid-Fire (Q → A)
- Is Map a Collection? → No.
- Root interface of collections? → Iterable.
- Ordered + duplicates? → List.
- Unique elements? → Set.
- Key-value? → Map.
- FIFO? → Queue. LIFO? → Deque/stack.
- Default ArrayList capacity? → 10 (lazy).
- ArrayList growth? → ~1.5×.
- ArrayList get complexity? → O(1).
- ArrayList add at index? → O(n).
- LinkedList get(i)? → O(n).
- LinkedList implements? → List and Deque.
- Best stack/queue impl? → ArrayDeque.
- Is ArrayDeque thread-safe? → No.
- PriorityQueue order? → Min-heap.
- PriorityQueue peek/poll? → O(1)/O(log n).
- HashSet backed by? → HashMap.
- TreeSet backed by? → TreeMap (red-black tree).
- TreeSet ordering needs? → Comparable/Comparator.
- NavigableSet methods? → floor, ceiling, higher, lower.
- LinkedHashSet preserves? → Insertion order.
- HashMap null keys? → One allowed.
- Hashtable null keys? → Not allowed.
- ConcurrentHashMap null? → No null keys/values.
- Default load factor? → 0.75.
- Default capacity? → 16.
- Treeify threshold? → 8 (with table ≥ 64).
- Untreeify threshold? → 6.
- Hash spreading formula? → h ^ (h >>> 16).
- Why power-of-two capacity? → Fast modulo via bitmask.
- Resize cost? → O(n) rehash.
- TreeMap complexity? → O(log n).
- NavigableMap methods? → firstKey, ceilingKey, subMap.
- EnumMap? → Array-backed, very fast, enum keys.
- EnumSet? → Bit-vector set of enums.
- IdentityHashMap? → Uses == not equals.
- WeakHashMap? → Keys GC'd when weakly reachable.
- Properties extends? → Hashtable.
- Collections.emptyList()? → Immutable empty list.
- Collections.singletonList()? → Immutable one-element list.
- List.of mutability? → Immutable.
- Arrays.asList mutability? → Fixed-size view.
- Convert array→list? → Arrays.asList / Arrays.stream.
- Convert list→array? → list.toArray(new T[0]).
- Sort a list? → Collections.sort / list.sort.
- Reverse a list? → Collections.reverse.
- Shuffle? → Collections.shuffle.
- Binary search list? → Collections.binarySearch (sorted).
- Min/max? → Collections.min/max.
- Frequency? → Collections.frequency.
- Unmodifiable wrapper? → Collections.unmodifiableX.
- Synchronized wrapper? → Collections.synchronizedX.
- CME stands for? → ConcurrentModificationException.
- modCount role? → Detects structural mods for fail-fast.
- removeIf? → Predicate-based safe removal.
- replaceAll on list? → Applies UnaryOperator.
- computeIfAbsent use? → Lazy default per key.
- merge use? → Combine existing+new value.
- getOrDefault? → Value or fallback.
- putIfAbsent? → Insert only if missing.
- entrySet vs keySet? → Pairs vs keys; entrySet faster for iteration.
- Map.Entry? → Key-value pair view.
- Iterate map? → for(var e: map.entrySet()).
- Immutable map? → Map.of / Map.copyOf.
- Map.of limit? → 10 pairs (use ofEntries beyond).
- Duplicate key in Map.of? → IllegalArgumentException.
- Null in List.of? → NPE.
- Capacity vs size? → Allocated buckets vs elements.
- Shrink ArrayList? → trimToSize().
- ensureCapacity? → Pre-allocate to avoid resizes.
- SubList view? → list.subList(a,b) (backed view).
- ListIterator extras? → add, set, previous.
- Spliterator? → Parallel-friendly traversal.
- Stream from collection? → collection.stream().
- Parallel stream pool? → Common ForkJoinPool.
- CopyOnWriteArraySet? → Set variant of COW list.
- ConcurrentSkipListMap? → Concurrent sorted map.
- ConcurrentLinkedQueue? → Lock-free unbounded queue.
- LinkedBlockingQueue bound? → Optional capacity.
- SynchronousQueue? → Zero capacity handoff.
- DelayQueue? → Elements available after delay.
- BlockingDeque? → Double-ended blocking queue.
- offer vs add? → offer returns false vs throws on capacity.
- poll vs remove? → poll returns null vs throws on empty.
- peek vs element? → peek null vs throws on empty.
- push/pop on Deque? → Stack ops at head.
- Why ArrayDeque > Stack? → No legacy sync, faster.
- Why ArrayList > Vector? → No legacy sync.
- Iterating + modifying fix? → Iterator.remove / removeIf / collect new.
- HashMap thread-safe alt? → ConcurrentHashMap.
- Sorted thread-safe map? → ConcurrentSkipListMap.
- TreeMap null key? → NPE (natural ordering).
- LinkedHashMap LRU? → accessOrder + removeEldestEntry.
- Best for counting frequencies? → HashMap + merge.
- Best for top-K? → PriorityQueue.
- Best for dedup preserving order? → LinkedHashSet.
- Best for range queries? → TreeMap/TreeSet.
- Initial-size a HashMap? → expected/0.75 + 1.
- Memory: ArrayList vs LinkedList? → LinkedList heavier (node overhead).
- Why immutable collections? → Safety, sharing, simplicity.
- equals/hashCode for keys? → Required for correct lookups.
- What breaks a HashSet? → Mutating elements' hash after add.
- contains() on list? → O(n).
- contains() on HashSet? → O(1) average.
- retainAll? → Intersection.
- removeAll? → Difference.
- addAll? → Union (with dups for list).
- disjoint? → Collections.disjoint.
- nCopies? → Immutable repeated list.
- Collectors.toUnmodifiableList? → Immutable result.
- groupingBy returns? → Map of lists.
- partitioningBy returns? → Map<Boolean, List>.
- toMap merge param? → Resolve duplicate keys.
- counting collector? → Frequency per group.
- Best concurrent counter map? → ConcurrentHashMap + merge/atomic.
- Weakly consistent iterator? → ConcurrentHashMap's.
- Fail-safe cost? → Snapshot memory/staleness.
- Capacity tuning benefit? → Fewer rehashes.
- Streaming a map? → map.entrySet().stream().
- Choosing a collection rule? → By access pattern: order, uniqueness, sorting, concurrency.