← The curriculum
§ 3.01 · Collections & Generics

Lists, Sets, Maps — the Collections framework

ArrayList, HashMap, HashSet, and the Iterable contract. Choose the right structure for the job.

Intermediate · 30 minute read
Try it yourself
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 3.01.01

The core interfaces

Collection is the root; List, Set, and Queue extend it, and Map sits alongside. Program to these interfaces, not to ArrayList or HashMap, so you can swap implementations without changing callers.

§ 3.01.02

List — ordered, indexable

ArrayList is the default. LinkedList exists but is rarely worth it. List.of(...) returns an immutable list — perfect for constants but throws if you try to mutate it.

§ 3.01.03

Set — uniqueness

HashSet gives O(1) membership tests but no order. LinkedHashSet preserves insertion order. TreeSet keeps elements in sorted order at O(log n). Choose by the guarantee you need.

§ 3.01.04

Map — key → value

HashMap is the default. LinkedHashMap preserves insertion order and can act as an LRU cache. TreeMap is sorted by key and supports range queries (headMap, tailMap, ceilingKey). Never rely on HashMap iteration order — it isn't specified.

§ 3.01.05

Iteration

Every collection implements Iterable, so enhanced for works everywhere. Modifying a collection while iterating throws ConcurrentModificationException; use Iterator.remove() or removeIf(...) instead.

Example
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 3.01.06

Choosing a structure

Need index access? ArrayList. Need dedupe? HashSet. Need lookup by key? HashMap. Need sorted iteration? TreeMap/TreeSet. Need FIFO/LIFO at both ends? ArrayDeque. When in doubt, start with ArrayList and HashMap — they're right 80% of the time.