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
| Operation | ArrayList | LinkedList | HashSet | TreeSet | HashMap | TreeMap |
|---|---|---|---|---|---|---|
| get by index | O(1) | O(n) | – | – | – | – |
| get by key/value | O(n) | O(n) | O(1) | O(log n) | O(1) | O(log n) |
| add at end | O(1)* | O(1) | O(1) | O(log n) | O(1) | O(log n) |
| add at front | O(n) | O(1) | – | – | – | – |
| remove by value | O(n) | O(n) | O(1) | O(log n) | O(1) | O(log n) |
| sorted iteration | O(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
LinkedListfor indexed access:get(500)walks 500 nodes.ArrayListis almost always the better list.equalswithouthashCode: Silent, baffling lookup failures.- Removing during a for-each loop: Throws
ConcurrentModificationException. UseIterator.remove()orremoveIf. HashMapshared across threads: Corrupts under concurrent writes. UseConcurrentHashMap.- 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/hashCodetogether, never one alone. - Return immutable views from getters to protect invariants.
Practice Exercises
- The Benchmark: Time 100,000
get(i)calls on anArrayListversus aLinkedListand explain the gap. - The Broken Set: Create a class with
equalsbut nohashCode, add two equal instances to aHashSet, and observe the size. - The Word Count: Count word frequencies in a paragraph using
mergein a single line inside the loop.