Chapter 11 of 16Foundation

The Collections Framework

Choose List, Set, or Map by contract, keep equals and hashCode consistent, and return safe collection views.

35 minJava 21
01

Why it matters

Start from the concept, not the syntax

Meet a concrete situation where this idea earns its place, then state the boundary it guards.

The Collections Framework answers one question in many ways: how do I hold many values? Lists keep order, sets reject duplicates, maps pair keys with values. Choosing by contract—and keeping equals and hashCode consistent—is the difference between collections that work and collections that surprise.

By the end of this chapter

Overriding equals without hashCode lets equal objects land in different buckets, breaking sets and maps silently.

  • List, Set, Map
  • equals and hashCode
  • Comparator ordering
02

Mechanism

How Java expresses the concept

Walk the actual types, rules, and runtime behavior involved—the same behavior described in the Java Language Specification.

The mental model

`List` is an ordered sequence with indexes; `ArrayList` is the usual default, while `LinkedList` is rarely the best choice because locating a position is still linear. Use `ArrayDeque` for queue or deque operations. `Set` holds unique elements (`HashSet` for speed, `TreeSet` for sorted order, `LinkedHashSet` for insertion order). `Map` associates keys to values (`HashMap` for speed, `TreeMap` for sorted keys).

Equality and hashing must agree. If you override `equals`, you must override `hashCode`, and both must use the same fields. Two equal objects must produce the same hash code, or they will live in different buckets and `HashSet`/`HashMap` will misbehave.

Iterate with the enhanced for loop or `forEach`. Prefer unmodifiable copies (`List.copyOf`, `Map.copyOf`) when returning collections from a method so callers cannot mutate the collection structure. The copy is shallow, so contained objects still need their own immutability or defensive copies. `Collections.unmodifiableList` is the older, weaker alternative.

`Comparable` defines natural ordering on the type itself; `Comparator` defines ordering outside the type and can be composed with `thenComparing`. Both drive `sort` and `TreeSet`/`TreeMap`.

03

Concept map

Inspect the building blocks as a whole

Use the map as a structural reference; it shows the pieces and their relationships, not an execution sequence.

Core Java

The Collections Framework

List, Set, and Map are the three collection families. Pick by contract: order, uniqueness, or key lookup.

  1. 01List / Set / Map
  2. 02ArrayList vs LinkedList
  3. 03HashSet / TreeSet
  4. 04HashMap / TreeMap
  5. 05equals and hashCode
  6. 06Comparable vs Comparator
04

Implementation

Encode the smallest runnable example

Write and run the code, then observe the behavior you just predicted with a real Java program.

Runnable snippet path

Predict, run, and change each example

2 focused examples
01

Choose a collection

A List keeps order and duplicates; a Set keeps only unique values.

Collect.java
import java.util.*;

public class Collect {
    static Set<String> unique(List<String> items) {
        return new LinkedHashSet<>(items);
    }
}

Remember

Override hashCode whenever you override equals, using the same fields.

Change one input, predict the result, then compile or test it before continuing.

02

Sort with a Comparator

Comparator.comparing pulls a key; thenComparing breaks ties.

Sort.java
import java.util.*;

record Person(String name, int age) {}

class Sort {
    static List<Person> byAge(List<Person> people) {
        var copy = new ArrayList<>(people);
        copy.sort(Comparator.comparing(Person::age));
        return copy;
    }
}

Remember

Sort a copy unless you intend to mutate the caller collection.

Change one input, predict the result, then compile or test it before continuing.

05

Watch out

Break it on purpose, then repair the right layer

Predict the symptom before running the failure case, and close with the completion checklist.

Deliberate failure

  1. Break

    Override equals but not hashCode on a class used as a map key

  2. Observe

    The same logical key is stored twice in a HashSet or never found again

  3. Repair

    Always override hashCode together with equals, using exactly the same fields for both

Why it matters

Always override hashCode together with equals, using exactly the same fields for both

Completion checklist

  • Pick a collection by its contract
  • Keep equals and hashCode consistent
  • Sort with Comparator or Comparable
06

Go deeper

Official references

The primary sources behind this chapter. Every claim above stays consistent with them.