02 · Objects and collections / LESSON 6 OF 102
Generics, List, Set, and Map
Select structures by the operations your program needs.
Before this lesson: Interfaces and constructor injection
Understand the topic
List preserves order and allows duplicates; Set keeps distinct values; Map associates keys with values. Generics such as List<String> enforce type checks at compile time. List.of returns an unmodifiable list.
HashMap offers average constant-time key lookup. Hash-based structures rely on equals and hashCode agreeing; do not mutate key equality while a key is stored. TreeMap orders its keys.
EXAMPLE · JAVA
Main.java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> topics = List.of("java", "sql", "java");
Map<String, Integer> counts = new TreeMap<>();
for (String topic : topics) counts.merge(topic, 1, Integer::sum);
counts.forEach((key, count) -> System.out.println(key + ": " + count));
}
}What to expect
java: 2, then sql: 1.
YOUR TURN
Put it into practice
- 01Deduplicate topics with a Set.
- 02Map task IDs to titles.
- 03Explain duplicate keys and iteration order.
Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.
UNDER THE HOOD
Build the mental model
Choose a collection from required operations, then consider ordering, equality, memory, and mutation.
- 01List lookup by index differs from searching by value. ArrayList indexed access is constant time; searching an unsorted list scans values.
- 02A hash lookup first selects a bucket using hashCode, then checks equality. Equal objects must have equal hash codes, but equal hash codes do not guarantee equality.
- 03Use immutable keys. If a key changes its hash after insertion, a map lookup may no longer find the entry.
A mistake worth avoiding
Do not rely on HashMap iteration order for deterministic API responses.
DEBUGGING ROOM
Something broke. Where do you look?
Two logically equal custom keys appear twice in a HashSet.
Before revealing the diagnosis, write down your first investigation step.
CHECK YOUR UNDERSTANDING
Two equal objects must have what relationship?
BUILD IT YOURSELF
Build a task index
- 1.Store tasks by immutable ID in a Map.
- 2.Provide lookup, replacement, and removal.
- 3.Return a sorted list when displaying results.
Acceptance checklist
Lab completion is your self-report. Knowledge checks do not certify project quality.
RETRIEVE IT FROM MEMORY
Why can mutating a map key break retrieval?
Revisit this lesson in three days after a successful check or lab.
Ready for the next step?
Choose a collection and explain its equality rules.
Reading is separate from passing a knowledge check or completing a lab.