SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

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.

17 Nov 20269 min readSenior

–

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.

JAVA
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 null key is allowed (bucket 0).
  • Concurrent puts into a HashMap can lose data.
  • ArrayList.remove(index) shifts elements with System.arraycopy, then nulls the last slot; forget that in your own structure and you leak memory.
  • modCount makes iterators fail-fast: modifying a list while iterating throws ConcurrentModificationException. It exposes bugs; it's not synchronisation.
  • ArrayList<Integer> costs many times more than int[] because of boxing (each Integer ~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:

  • HashMap keys and HashSet elements are immutable (records, String).
  • No Stack, Vector or Hashtable in new code.
  • Queues between producers and consumers are bounded.
  • No HashMap written by several threads.
  • No modifying a collection inside for-each; use removeIf or Iterator.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.

JAVA
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
  • capacity is never assigned and stays 0. The first time size == capacity holds and the array grows to 1. The second time size = 1 ≠ 0, so it doesn't grow, and array[1] throws ArrayIndexOutOfBoundsException.
  • 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

  • ArrayList grows ~1.5×, so appending is O(1) amortized.
  • LinkedList is rarely right; use ArrayDeque for stacks and queues.
  • HashMap: hash & (n - 1), trees at ≥ 8 per bucket in tables ≥ 64, doubling above 0.75.
  • Keys must be immutable; use ConcurrentHashMap across threads.
  • Production queues are bounded so you get backpressure.

Read more: Part 3: TreeMap, Comparator, iterators.

Practice interview questions on this topic

All Collections & DSA questions →

Loading comments…
Next on the roadmapBasic algorithms: Big-O and the three O(n²) sorts