Inside Java Collections: ArrayList, LinkedList, ArrayDeque and HashMap
How ArrayList grows, why LinkedList and Stack are rarely the right choice, how HashMap hashes, treeifies and resizes, Java 21 Sequenced Collections, a Big-O cheat sheet, and building ArrayList and LinkedList yourself.
On this page
1. The problem
A login-session cache uses HashMap<Session, User> where Session has a lastSeen field used in hashCode. Every update to lastSeen makes the entry "vanish": get returns null, the map grows to 2 million entries nobody can retrieve, then OutOfMemoryError.
2. Key idea
Each collection is a concrete structure: an array, a circular array, a linked list, a hash table. Know the structure and you can derive its costs and traps.
| Structure | Inside | Trap |
|---|---|---|
ArrayList |
an array; when full, a new old + (old >> 1) array and a copy |
each resize is O(n): latency spikes |
LinkedList |
doubly linked nodes (item, next, prev) | get(i) is O(n); poor cache use; harder on GC |
ArrayDeque |
a circular array, head/tail wrap around |
no null allowed |
HashMap |
a power-of-two bucket array, lists or trees per bucket | mutable keys; a constant hashCode() piles every key into one bucket |
Geometric growth makes the total copying for n adds O(n). Constant growth (+10 each time) is the real mistake: O(n²).
2.1 What to use when?
| Need | Use when | Don't use when |
|---|---|---|
ArrayList |
index access, appending; if the size is known, new ArrayList<>(n) |
constant inserts and removals at the front |
ArrayDeque |
single-threaded stacks and queues | you need null or multiple threads |
HashMap |
lookup by key, O(1) on average | multiple threads: ConcurrentHashMap |
TreeMap |
ordered keys, ranges | exact lookup only |
ArrayBlockingQueue |
producer/consumer with backpressure | unbounded queues: work piles up until OOM |
List.of(...) is immutable; Arrays.asList(...) is fixed-size and wraps the original array.
3. In Java
Immutable keys, a bounded queue, a stack on ArrayDeque.
record SessionKey(String id) {} // record: equals and hashCode on id, immutable
Map<SessionKey, User> sessions = new HashMap<>();
sessions.put(new SessionKey("s1"), user);
sessions.get(new SessionKey("s1")); // user
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
stack.pop(); // 2
BlockingQueue<Job> jobs = new ArrayBlockingQueue<>(1_000);
jobs.offer(job, 100, TimeUnit.MILLISECONDS); // false when full: report overload instead of OOM
List<Integer> ids = new ArrayList<>(10_000); // known size: no resizing
ids.getLast(); // Java 21, instead of ids.get(ids.size() - 1)Other languages: Go map and slices (append also grows geometrically); Python dict and list follow the same ideas.
HashMap and ArrayList: details interviewers ask about
- The hash is mixed with
h ^ (h >>> 16)because& (n - 1)only uses the low bits. The table is always a power of two so&can replace%. - On doubling, each entry either keeps its index or moves by exactly
oldCapacity; no full rehash needed. - Below 64 slots the table resizes instead of treeifying; a tree shrinking to 6 nodes turns back into a list. One
nullkey is allowed (bucket 0). - Concurrent
puts into aHashMapcan lose data. ArrayList.remove(index)shifts elements withSystem.arraycopy, then nulls the last slot; forget that in your own structure and you leak memory.modCountmakes iterators fail-fast: modifying a list while iterating throwsConcurrentModificationException. It exposes bugs; it's not synchronisation.ArrayList<Integer>costs many times more thanint[]because of boxing (eachInteger~16 bytes).
4. Working with AI
Hand to AI: picking collections by access pattern, JMH performance tests, reimplementing a structure to learn it.
Check in AI-written code:
-
HashMapkeys andHashSetelements are immutable (records,String). - No
Stack,VectororHashtablein new code. - Queues between producers and consumers are bounded.
- No
HashMapwritten by several threads. - No modifying a collection inside for-each; use
removeIforIterator.remove().
5. Exercises
Exercise 1: Review a hand-written ArrayList
The AI wrote this, saying "tested adding one element". Find the bugs, name a test that proves them, fix it.
class MyList {
private Object[] array = new Object[0];
private int size, capacity;
void add(Object e) {
if (size == capacity) array = Arrays.copyOf(array, array.length + 1);
array[size++] = e;
}
}Solution to Exercise 1
capacityis never assigned and stays 0. The first timesize == capacityholds and the array grows to 1. The second timesize = 1 ≠ 0, so it doesn't grow, andarray[1]throwsArrayIndexOutOfBoundsException.- Growing by one slot (even with the condition fixed) is constant growth: n
adds cost O(n²) copying.
Test: add 3 elements and check size() == 3; plus a 100,000-element test that measures time.
Fix: drop capacity and compare size == array.length; grow to Math.max(10, old + (old >> 1)); use a generic <E>.
Exercise 2: Read a growing-map incident
After a release the heap grows 200 MB an hour; the histogram shows HashMap$Node climbing without end, held by SessionCache.map. The code does map.put(session, user) at login, session.touch() (updating lastSeen) on every request, and map.get(session) to check. Diagnose and fix.
Solution to Exercise 2
Diagnosis: lastSeen is part of hashCode. After touch() the hash changes, get looks in the wrong bucket and returns null; the login path then puts a new entry. The old entries stay in the map but nobody can reach them: a memory leak.
Fix: make the key record SessionKey(String id), immutable; keep lastSeen in the value. Use a bounded cache with a TTL (Caffeine) instead of a bare HashMap. Add a test: put, change state, get still works.
Summary
ArrayListgrows ~1.5×, so appending is O(1) amortized.LinkedListis rarely right; useArrayDequefor stacks and queues.HashMap:hash & (n - 1), trees at ≥ 8 per bucket in tables ≥ 64, doubling above 0.75.- Keys must be immutable; use
ConcurrentHashMapacross threads. - Production queues are bounded so you get backpressure.
Read more: Part 3: TreeMap, Comparator, iterators.
Practice interview questions on this topic
- How do ArrayList and LinkedList differ, and when do you use each?
- How does HashMap work internally in Java 8+?
- What happens if you mutate an object used as a HashMap key or stored in a TreeSet?
- How is ConcurrentHashMap (Java 8+) thread-safe on the inside?
- How would you build an LRU cache with Java Collections?
- What is in the Java Collections Framework? How do List, Set, Map and Queue differ?
Comments
Community rules