← All lessons
Advanced Java · Lesson 3 of 9

How collections work inside

Choosing the right collection can make a program thousands of times faster. To choose well you need to know roughly how each one works inside and how its speed changes as it grows. That's what Big O describes: O(1) means the time stays the same however big the data, O(log n) grows very slowly, O(n) grows in step with the data, and O(n²) grows with its square, so ten times the data takes a hundred times as long.

ArrayList

An ArrayList keeps its items in an ordinary array. Reading or writing by index is O(1): the item's place is worked out directly. Adding at the end is usually O(1) too: the array has spare room, and when it fills up the list makes a new one about 1.5 times bigger and copies everything across. That copy is slow, but rare enough that it averages out. Inserting or removing near the front is O(n), because every later item shifts along one place. contains and indexOf are O(n): they look at each item in turn.

HashMap

A HashMap keeps an array of buckets. To store a key it calls hashCode(), turns that number into a bucket index and puts the entry there. To find a key it does the same sum, goes straight to that bucket and uses equals() to pick the right entry among the few there. So get, put and containsKey are O(1) on average, however many entries there are. When the map gets three-quarters full it doubles the buckets and spreads the entries out again.

That's why equals and hashCode must agree: equal keys must give the same hash code, or the map looks in the wrong bucket. And it's why a key must not change after it's put in: its hash code would change and the map would never find it again.

Java
public class Main {
    static class Key {
        String id;
        Key(String id) { this.id = id; }
        @Override public boolean equals(Object o) { return o instanceof Key k && k.id.equals(id); }
        @Override public int hashCode() { return id.hashCode(); }
    }

    public static void main(String[] args) {
        Map<Key, String> m = new HashMap<>();
        Key k = new Key("a");
        m.put(k, "first");
        System.out.println(m.get(new Key("a")));
        k.id = "b";
        System.out.println(m.get(k) + " " + m.get(new Key("a")) + " " + m.size());
    }
}
Prints
first
null null 1

After the key's field changed, the entry is still in the map but under the old hash, so neither lookup finds it: a quiet memory leak. Records and strings can't change, which makes them safe keys.

Other structures

  • LinkedList: items in nodes, each pointing at the next and previous. Adding or removing at either end is O(1), but reaching item i means walking from an end, O(n). In practice ArrayList is faster for almost everything.
  • ArrayDeque: a growable array used from both ends. The best choice for a stack (push and pop) or a queue (offer and poll); all O(1).
  • TreeMap and TreeSet: a balanced tree that keeps keys sorted. get and put are O(log n), a bit slower than hashing, but you get order: firstKey, headMap, ceilingKey and friends.
  • PriorityQueue: a heap that always hands back the smallest item next (or the first by a comparator) in O(log n). Used for schedulers, "top 10" and shortest paths.
Java
Deque<String> stack = new ArrayDeque<>();
stack.push("a"); stack.push("b"); stack.push("c");
System.out.println(stack.pop() + stack.pop());
Queue<String> queue = new ArrayDeque<>(List.of("first", "second"));
queue.offer("third");
System.out.println(queue.poll() + " " + queue.size());
PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(40, 10, 30, 20));
System.out.println(pq.poll() + " " + pq.poll());
TreeMap<Integer, String> grades = new TreeMap<>(Map.of(90, "A", 80, "B", 70, "C", 0, "D"));
System.out.println(grades.floorEntry(85).getValue() + grades.floorEntry(91).getValue() + grades.floorEntry(12).getValue());
Prints
cb
first 2
10 20
BAD

floorEntry(85) finds the biggest key at most 85, which is 80: a grade lookup in one line, thanks to the sorted tree.

Changing a collection while looping

Removing items from a list inside a for-each loop over the same list throws ConcurrentModificationException: the loop notices the list changed under it. Use removeIf, an explicit Iterator with its own remove(), or build a new list.

Java
List<Integer> xs = new ArrayList<>(List.of(1, 2, 3, 4));
try {
    for (Integer x : xs) if (x % 2 == 0) xs.remove(x);
} catch (ConcurrentModificationException e) {
    System.out.println("ConcurrentModificationException");
}
xs = new ArrayList<>(List.of(1, 2, 3, 4));
Iterator<Integer> it = xs.iterator();
while (it.hasNext()) if (it.next() % 2 == 0) it.remove();
System.out.println(xs);
Prints
ConcurrentModificationException
[1, 3]

List.of, Map.of and .toList() give unmodifiable collections: adding to one throws UnsupportedOperationException. That's a feature: pass one around and nobody can change it behind your back.

  1. the key"ana"
  2. hashCode()a number from the key
  3. bucket indexthe number, fitted to the array
  4. equals()on the few entries in that bucket
  5. the value
How HashMap.get finds a key

Practice

Which operation is slow (O(n)) on an ArrayList with a million items?

More info

Quick reference

O(1) / O(log n) / O(n) / O(n²)Same time / very slow growth / in step / with the square.
ArrayListIndex O(1), add at end O(1) on average, insert at front O(n).
HashMap / HashSetget, put, contains O(1) on average, via hashCode then equals.
TreeMap / TreeSetSorted; O(log n); floorKey, ceiling, headSet.
ArrayDequeStack (push, pop) or queue (offer, poll).
PriorityQueuepoll gives the smallest next.
ConcurrentModificationExceptionChanged a collection while looping over it.
List.of / Map.ofUnmodifiable collections.

Related courses