Loslegen
Javaneer
Zurück zur Stufe
Stufe 3·Java für Fortgeschrittene

The Collections Framework

List, Set, Map, and Queue with animated internals, and how to choose the right one.

24 Min. LesezeitFortgeschritten

Deutsche Übersetzung in Arbeit

Diese Lektion ist noch nicht ins Deutsche übersetzt und wird daher auf Englisch angezeigt. Der Rest der Seite ist vollständig lokalisiert.

Auf dieser Seite

Arrays have a fixed size - but real programs need lists that grow, sets that reject duplicates, and maps that pair keys with values. That's the Collections Framework: Java's toolkit of powerful, ready-made data structures.

The big four

InterfaceHoldsKey trait
ListOrdered items, duplicates OKAccess by index
SetUnique itemsNo duplicates
MapKey → value pairsLook up by key
QueueItems in lineFirst-in, first-out
Choosing a collection is like choosing a container
  • A List is a numbered shopping list - order matters, repeats are fine.
  • A Set is a bag of unique stamps - add the same one twice, still one.
  • A Map is a dictionary - look up a word (key) to get its definition (value).
  • A Queue is a line at a coffee shop - first come, first served.

List: the everyday workhorse

ArrayList is the go-to list. It grows automatically:

List<String> tasks = new ArrayList<>();
tasks.add("Write code");
tasks.add("Test code");
tasks.add("Write code");        // duplicates allowed

System.out.println(tasks.get(0));    // Write code
System.out.println(tasks.size());    // 3
tasks.remove("Test code");

for (String task : tasks) {
    System.out.println(task);
}

ArrayList vs. LinkedList

ArrayList stores items in a resizable array - fast random access by index. LinkedList chains nodes together - faster inserts/removals at the ends, but slow index access. For 95% of cases, ArrayList is the right default.

Set: no duplicates allowed

Set<String> visitors = new HashSet<>();
visitors.add("Ada");
visitors.add("Grace");
visitors.add("Ada");            // ignored - already present

System.out.println(visitors.size());        // 2
System.out.println(visitors.contains("Ada")); // true
  • HashSet - fastest, no order.
  • LinkedHashSet - keeps insertion order.
  • TreeSet - keeps items sorted.

Map: keys to values

HashMap is the most-used collection of all - pairing keys with values:

Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
ages.put("Grace", 45);

System.out.println(ages.get("Ada"));            // 36
System.out.println(ages.getOrDefault("Bob", 0)); // 0 (Bob absent)
ages.put("Ada", 37);                            // overwrites

for (var entry : ages.entrySet()) {
    System.out.println(entry.getKey() + " → " + entry.getValue());
}
A HashMap is like a coat check

Hand over your coat (value) and get a numbered ticket (key). Later, present the ticket and instantly retrieve your coat - no searching through every coat. That near-instant lookup is what makes HashMap so powerful. Under the hood, it uses your key's hashCode() to jump straight to the right "bucket".

Keys need correct equals & hashCode

Because HashMap and HashSet use hashCode() and equals() to place and find items, your key objects must implement them correctly (remember the OOP equality lesson!). Records and Strings already do this for you.

Choosing the right collection

Ask yourself:

  1. Do I need key → value pairs?Map (usually HashMap).
  2. Must items be unique?Set (usually HashSet).
  3. Do I need order and indexing, with duplicates?List (usually ArrayList).
  4. First-in-first-out processing?Queue (e.g. ArrayDeque).

Program to the interface

Declare variables by the interface, not the concrete class: List<String> x = new ArrayList<>();. This lets you swap implementations later without changing the rest of your code - the "program to interfaces" principle in action.

Quick check

You need to count unique visitors to a website, rejecting duplicates automatically. Which collection?

Key takeaways

  • The Collections Framework provides List, Set, Map, and Queue - resizable, powerful data structures.
  • List (ArrayList) keeps ordered items with duplicates and index access.
  • Set (HashSet) stores unique items; Map (HashMap) pairs keys with values for fast lookup.
  • HashMap/HashSet rely on correct hashCode() and equals() for their keys/elements.
  • Pick by need: pairs -> Map, uniqueness -> Set, ordered+indexed -> List, FIFO -> Queue.
  • Declare variables by the interface (List, Map) to keep implementations swappable.

Ever noticed the <String> and <String, Integer> in angle brackets? That's generics - the topic of our next lesson.