Appearance
Lesson 03 · Core Collections
Objectives
After this lesson you will be able to:
- Choose between
List,Set,Map,Queue/Dequeand their main implementations. - Use factory methods (
List.of,Map.of) and know their immutability. - Iterate and remove safely.
The framework at a glance
| Interface | Meaning | Common impls |
|---|---|---|
List | ordered, indexed, duplicates OK | ArrayList, LinkedList |
Set | no duplicates | HashSet, LinkedHashSet, TreeSet |
Map | key → value (not a Collection) | HashMap, LinkedHashMap, TreeMap |
Queue/Deque | FIFO / double-ended | ArrayDeque, LinkedList |
HashSet/HashMap are unordered; the Linked* variants keep insertion order; the Tree* variants keep sorted order (and require Comparable elements/keys or a Comparator).
java
List<String> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<String,Integer> map = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>(); // push/pop/peekFactory methods (immutable)
List.of, Set.of, Map.of build compact unmodifiable collections.
java
List<Integer> xs = List.of(1, 2, 3);
xs.add(4); // UnsupportedOperationException — immutable
Map<String,Integer> m = Map.of("a", 1, "b", 2);Exam trap
List.of(...) etc. are immutable: any mutator throws UnsupportedOperationException. They also reject null elements/keys (NPE), unlike ArrayList/HashMap. Set.of/Map.of throw IllegalArgumentException on duplicate elements/keys.
Useful Map methods
java
map.getOrDefault("x", 0);
map.putIfAbsent("a", 1);
map.computeIfAbsent("k", key -> new ArrayList<>()).add(v); // multimap idiom
map.merge("a", 1, Integer::sum); // counter idiomIterating and removing safely
Removing during a for-each throws ConcurrentModificationException (Module 02). Use an Iterator or removeIf:
java
list.removeIf(s -> s.isBlank());
for (var it = list.iterator(); it.hasNext(); ) {
if (cond(it.next())) it.remove();
}SDET note
For deterministic tests, prefer ordered implementations (LinkedHashMap/LinkedHashSet) or sort before asserting — HashMap/HashSet iteration order is unspecified and can differ across JVMs, making assertEquals on a toString() flaky.
Key Takeaways
List(indexed, dup OK),Set(no dups),Map(key→value, not aCollection),Queue/Deque(FIFO/double-ended).Linked*keep insertion order;Tree*keep sorted order.List.of/Set.of/Map.ofare immutable, rejectnull, and (Set/Map) reject duplicates — mutating throwsUnsupportedOperationException.- Use
getOrDefault/computeIfAbsent/mergefor commonMappatterns. - Remove during iteration with
Iterator.remove()orremoveIf, never inside a for-each.
Lesson Quiz
What does List.of(1,2).add(3) do?
Which Set keeps elements in SORTED order?
What does Map.of("a",1).put("b",2) throw?
Which idiom safely accumulates into a multimap?
Is List.of(1, null, 2) legal?
Next: Sequenced Collections. Run the matching code in labs/src/main/java/com/jse21/m05_collections/.