Choosing Collections: Performance Matters

Choosing Collections: Performance Matters in Java: Every collection makes a trade-off. Choosing wrongly turns an O(1) operation into O(n), which is invisible…

Concept Explanation

Every collection makes a trade-off. Choosing wrongly turns an O(1) operation into O(n), which is invisible with 10 items and fatal with 100,000.


The Complexity Table

OperationArrayListLinkedListHashSetTreeSetHashMapTreeMap
get by indexO(1)O(n)––––
get by key/valueO(n)O(n)O(1)O(log n)O(1)O(log n)
add at endO(1)*O(1)O(1)O(log n)O(1)O(log n)
add at frontO(n)O(1)––––
remove by valueO(n)O(n)O(1)O(log n)O(1)O(log n)
sorted iterationO(n log n)O(n log n)–O(n)–O(n)

\* amortised — occasionally the backing array is resized and copied.


Decision Guide

// Indexed access, iteration — the default choice
List<String> names = new ArrayList<>();

// Heavy insertion/removal at the ends — a queue or deque
Deque<Task> queue = new ArrayDeque<>();       // faster than LinkedList in practice

// Uniqueness, order irrelevant
Set<String> seen = new HashSet<>();

// Uniqueness, sorted
NavigableSet<String> sorted = new TreeSet<>();

// Uniqueness, insertion order preserved
Set<String> ordered = new LinkedHashSet<>();

// Key-value lookup
Map<String, User> byId = new HashMap<>();

// Key-value, sorted by key, with range queries
NavigableMap<LocalDate, Event> calendar = new TreeMap<>();

// Key-value, thread-safe
Map<String, Integer> counters = new ConcurrentHashMap<>();

The equals/hashCode Contract

HashMap and HashSet are useless without it:

public class Point {
    private final int x, y;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);     // MUST be consistent with equals
    }
}

Override equals without hashCode and your objects vanish inside hash collections — you add one and contains returns false. Records generate both correctly, which is one good reason to use them.

Never use a mutable field in hashCode. Mutating it after insertion puts the object in the wrong bucket, and it becomes unreachable.


Useful Map Methods

map.getOrDefault("key", 0);
map.putIfAbsent("key", 1);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);   // multimap idiom
map.merge(word, 1, Integer::sum);                              // word counting
map.forEach((k, v) -> System.out.println(k + "=" + v));

The computeIfAbsent line replaces the classic five-line null check.


Immutable Collections

List<String> fixed = List.of("a", "b", "c");     // throws on modification
Map<String, Integer> m = Map.of("a", 1, "b", 2);
List<String> copy = List.copyOf(mutableList);    // defensive snapshot

Return these from getters so callers cannot mutate your internal state.


Common Mistakes

  1. LinkedList for indexed access: get(500) walks 500 nodes. ArrayList is almost always the better list.
  2. equals without hashCode: Silent, baffling lookup failures.
  3. Removing during a for-each loop: Throws ConcurrentModificationException. Use Iterator.remove() or removeIf.
  4. HashMap shared across threads: Corrupts under concurrent writes. Use ConcurrentHashMap.
  5. Mutable keys: Change a key's state and its entry becomes unreachable.

Best Practices

  • Declare the interface, instantiate the implementation: List<T> x = new ArrayList<>().
  • Presize when you know the size: new ArrayList<>(10_000) avoids repeated resizing.
  • Use records or generate equals/hashCode together, never one alone.
  • Return immutable views from getters to protect invariants.

Practice Exercises

  1. The Benchmark: Time 100,000 get(i) calls on an ArrayList versus a LinkedList and explain the gap.
  2. The Broken Set: Create a class with equals but no hashCode, add two equal instances to a HashSet, and observe the size.
  3. The Word Count: Count word frequencies in a paragraph using merge in a single line inside the loop.