Java Collections Framework
List, Set, Queue, Deque and Map — the main implementations, their complexities and internals (ArrayList growth, HashMap buckets and treeification, TreeMap), iteration, immutability, and choosing the right one.
The Java Collections Framework is a set of interfaces (what a collection can do) and implementations (how). Knowing their internals and complexities is essential for both performance and interviews.
Choosing quickly
| Need | Use |
|---|---|
| Ordered, indexable, mostly appends | ArrayList |
| Unique elements, fast lookup | HashSet |
| Unique + insertion order | LinkedHashSet |
| Sorted unique / range queries | TreeSet |
| Key → value lookup | HashMap |
| Map with insertion or access order (LRU) | LinkedHashMap |
| Sorted map, floor/ceiling, ranges | TreeMap |
| Stack or queue (FIFO/LIFO) | ArrayDeque |
| Always get the min/max | PriorityQueue |
| Concurrent map | ConcurrentHashMap |
Complexity cheat sheet
| Operation | ArrayList | LinkedList | HashMap/HashSet | TreeMap/TreeSet | PriorityQueue | ArrayDeque |
|---|---|---|---|---|---|---|
| get by index | O(1) | O(n) | — | — | — | — |
| add at end | O(1) amortised | O(1) | — | — | — | O(1) |
| add/remove at front | O(n) | O(1) | — | — | — | O(1) |
| insert/remove middle | O(n) | O(n) to find, O(1) to link | — | — | — | — |
| contains / get(key) | O(n) | O(n) | O(1) average | O(log n) | O(n) | O(n) |
| put / add | — | — | O(1) average | O(log n) | O(log n) | — |
| min / max | O(n) | O(n) | O(n) | O(log n) | O(1) peek | — |
| iterate in sorted order | sort first | sort first | no order | yes | no | — |
List
ArrayList internals
Backed by an Object[]. When full, it grows by 1.5× and copies — so add is O(1) amortised. Random access is a direct array index, and contiguous memory makes iteration cache-friendly.
List<String> names = new ArrayList<>(1000); // pre-size if you know the count
names.add("Ada");
names.get(0);
names.remove("Ada"); // by value, O(n)
names.remove(0); // by index — beware List<Integer>: remove(0) vs remove(Integer.valueOf(0))
Collections.sort(names); // or names.sort(Comparator.naturalOrder())LinkedList
A doubly linked list. Despite O(1) insertion at known nodes, it's rarely faster in practice: each node is a separate object (extra memory, poor cache locality), and finding a position is O(n). Use ArrayDeque for queues and ArrayList otherwise.
Map
HashMap internals
An array of buckets. put(k, v): compute k.hashCode(), spread the bits (h ^ (h >>> 16)), pick bucket hash & (capacity − 1) (capacity is a power of two), then store in that bucket's list.
- Load factor 0.75: when size > capacity × 0.75, the table doubles and entries are redistributed (each splits between index i and i + oldCapacity).
- Treeification (Java 8+): a bucket with ≥ 8 entries (and table ≥ 64) becomes a red-black tree, so worst-case lookup is O(log n) instead of O(n) — protection against bad hashes and hash-flooding attacks.
- Allows one
nullkey and null values. Not thread-safe: concurrent modification can corrupt it. - Iteration order is unspecified and can change after resizing.
Useful Map methods
Map<String, Integer> counts = new HashMap<>();
for (String w : words) counts.merge(w, 1, Integer::sum); // word count in one line
Map<String, List<Order>> byCustomer = new HashMap<>();
byCustomer.computeIfAbsent(o.customer(), k -> new ArrayList<>()).add(o); // multimap
counts.getOrDefault("missing", 0);
counts.putIfAbsent("x", 0);
for (var e : counts.entrySet()) System.out.println(e.getKey() + "=" + e.getValue());LinkedHashMap and TreeMap
// LRU cache in a few lines: accessOrder = true + removeEldestEntry
class Lru<K, V> extends LinkedHashMap<K, V> {
private final int cap;
Lru(int cap) { super(16, 0.75f, true); this.cap = cap; }
@Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > cap; }
}
// TreeMap: a red-black tree with navigation methods
TreeMap<Integer, String> grades = new TreeMap<>(Map.of(90, "A", 80, "B", 70, "C", 0, "F"));
grades.floorEntry(85).getValue(); // "B" — greatest key <= 85
grades.ceilingKey(71); // 80
grades.headMap(80); // keys < 80
grades.firstKey(); grades.pollLastEntry();Set
HashSet is literally a HashMap with dummy values; TreeSet wraps a TreeMap. Same complexities and same rules about equals/hashCode (or compareTo for tree-based).
Queue, Deque and PriorityQueue
Deque<Integer> stack = new ArrayDeque<>(); // use instead of the legacy Stack class
stack.push(1); stack.push(2); stack.pop(); // 2
Queue<Integer> queue = new ArrayDeque<>(); // BFS queue
queue.offer(1); queue.poll();
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); // min-heap by second element
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());PriorityQueue is a binary heap in an array: offer/poll O(log n), peek O(1), but iterating it does not give sorted order. Beware (a, b) -> a - b comparators with large values (overflow); use Integer.compare.
Immutable and unmodifiable collections
List<String> fixed = List.of("a", "b"); // immutable; nulls not allowed
Map<String, Integer> m = Map.of("a", 1, "b", 2);
List<String> copy = List.copyOf(mutableList); // immutable snapshot
List<String> view = Collections.unmodifiableList(mutableList); // read-only VIEW: changes to the source show through
Arrays.asList(arr); // fixed-size view backed by the array: set() works, add() throwsIteration and modification
for (String s : list) if (s.isEmpty()) list.remove(s); // ConcurrentModificationException!
list.removeIf(String::isEmpty); // correct
Iterator<String> it = list.iterator();
while (it.hasNext()) if (it.next().isEmpty()) it.remove(); // also correctIterators are fail-fast: they track a modification count and throw if the collection changes underneath them (best-effort, not a concurrency guarantee).
Concurrent collections
| Class | Use |
|---|---|
ConcurrentHashMap | High-concurrency map; lock-free reads, per-bin locking for writes; atomic compute/merge |
CopyOnWriteArrayList | Read-mostly lists (listeners); each write copies the array |
ConcurrentLinkedQueue | Lock-free unbounded queue |
ArrayBlockingQueue, LinkedBlockingQueue | Producer–consumer with blocking put/take |
ConcurrentSkipListMap | Concurrent sorted map |
Collections.synchronizedMap wraps every method in one lock — simple but slow under contention; prefer ConcurrentHashMap (Java concurrency).
- ArrayList for lists, ArrayDeque for stacks/queues, HashMap/HashSet for lookup, TreeMap for order and ranges.
- ArrayList grows 1.5×; HashMap doubles at load factor 0.75 and treeifies long buckets.
- Keys need correct, stable equals/hashCode (or compareTo).
- List.of/Map.of are immutable; Arrays.asList is fixed-size; unmodifiable views reflect changes.
- Use removeIf or the iterator to remove while iterating; ConcurrentHashMap for concurrency.
QHow does HashMap work internally?medium
It keeps an array of buckets whose size is a power of two. A key's hashCode is mixed (h ^ h>>>16) and masked to choose a bucket. Entries in a bucket form a linked list; with 8 or more entries (and capacity at least 64) the bucket becomes a red-black tree. get and put compare hashes then equals. When size exceeds capacity × 0.75, the table doubles and entries are redistributed. Average O(1), worst case O(log n) with treeification.
QArrayList vs LinkedList?easy
ArrayList is a resizable array: O(1) random access, amortised O(1) appends, O(n) inserts in the middle, compact and cache-friendly. LinkedList is a doubly linked list: O(1) insertion at a known node or the ends but O(n) access and high per-node memory overhead. In practice ArrayList (or ArrayDeque for queues) is almost always faster.
QHashMap vs ConcurrentHashMap vs Hashtable?medium
HashMap is unsynchronised and allows a null key. Hashtable is a legacy class with every method synchronised on one lock and no nulls. ConcurrentHashMap allows concurrent reads without locking and locks only individual bins on writes (CAS for empty bins), offers atomic compute/merge operations, and disallows nulls. Use ConcurrentHashMap for shared maps.