The Collections Framework is a set of interfaces plus implementations that honour documented complexity and mutability. Program to List, Set, Map, Deque — not to ArrayList — unless you need an ArrayList-only method or a constructor argument that documents expected growth.
| Interface | Allows duplicates | Order | Nulls (typical impls) |
|---|---|---|---|
| List | yes | insertion / index | ArrayList/LinkedList: yes |
| Set | no (equals) | HashSet: none; LinkedHashSet: insert; TreeSet: sorted | HashSet: one null; TreeSet: no (compareTo) |
| Map | unique keys | analogous to Set of keys | HashMap: one null key; ConcurrentHashMap: no nulls |
| Deque / Queue | yes | ends / FIFO | varies — ArrayDeque: no nulls |
Mental model: a collection is a live object. Passing it to a method passes a reference. If you did not copy or wrap it, the callee can change “your” list.
| Need | Choose | Avoid for this need |
|---|---|---|
| Indexed list, random access | ArrayList | LinkedList (almost always slower) |
| Frequent insert at 0 of a huge list | Measure; often still ArrayList + reverse, or ArrayDeque | LinkedList by habit |
| Membership, unique values | HashSet | List.contains in a loop (O(n)) |
| Stable iteration order of a set/map | LinkedHashSet / LinkedHashMap | relying on HashMap order (not a contract before sequenced collections) |
| Sorted unique | TreeSet / TreeMap (compareTo) | HashSet plus a later sort if you needed order all along |
| Enum keys | EnumSet / EnumMap | HashMap<Enum, …> without a reason |
| Queue / stack in one thread | ArrayDeque | Stack (legacy, synchronized), LinkedList |
Complexity (ArrayList): get/set O(1); add at end amortized O(1); add/remove at index O(n). HashMap: expected O(1) get/put if hashCode is sound; worst case degrades (Java 8+ treeifies colliding bins). TreeMap: O(log n).
LinkedList: almost never the right default in modern Java. It is a teaching type and a few genuine deque cases you can serve with ArrayDeque.
Java 9+: List.of, Set.of, Map.of / Map.ofEntries. They reject nulls. Set/Map reject duplicate keys at construction. They are unmodifiable — add throws UnsupportedOperationException. They are not necessarily ArrayList.
List<String> ok = List.of("a", "b");
List<String> copy = List.copyOf(mutable); // snapshot, rejects nulls
Map<String, Integer> m = Map.of("a", 1, "b", 2); // up to 10 pairs; then ofEntries
Collections.unmodifiableList(live) is a view: changes to live appear. List.copyOf is a snapshot (and is a no-op if the argument is already an unmodifiable List from these factories).stream.toList() is unmodifiable. Java 8: collect(toList()) is a mutable ArrayList (not specified, but the usual implementation) — do not rely on mutability either way; copy if you must mutate.SequencedCollection adds getFirst/addLast/reversed to List and LinkedHashMap/Set. On 17, use index 0 / get(size-1).for (String s : list) { } // iterator
list.forEach(this::use); // may be faster; still fail-fast on ArrayList
for (var e : map.entrySet()) { e.getKey(); e.getValue(); }
map.forEach((k, v) -> { });
Iterator.remove, next() throws ConcurrentModificationException. This is a best-effort check (modCount), not a guarantee, and not a thread-safety mechanism.iterator.remove(), removeIf, or collect ids and remove after.// Incorrect for (String s : list) if (s.isBlank()) list.remove(s); // Correct list.removeIf(String::isBlank);
map.getOrDefault(k, 0); map.putIfAbsent(k, new ArrayList<>()); map.computeIfAbsent(k, key -> new ArrayList<>()).add(item); map.merge(k, 1, Integer::sum); map.replaceAll((k, v) -> v.strip());
get returns null for missing or a null value — HashMap allows both. Prefer containsKey or Optional wrappers at your boundary. ConcurrentHashMap forbids null keys and values so get == null means absent.computeIfAbsent must not modify the same map in the function on some implementations (ConcurrentHashMap documents this). Keep the function pure.entrySet, not keySet plus get (two lookups).Synchronizing every call on an ArrayList (Collections.synchronizedList) is not a design. Compound actions (check-then-act) still race. Prefer a concurrent collection or a single-thread owner.
| Type | Use | Notes |
|---|---|---|
ConcurrentHashMap | Shared map | No nulls. Iterators are weakly consistent (no CME, may see updates). Size is an estimate under contention. |
CopyOnWriteArrayList | Rare writes, many reads (listeners) | Every write copies the array. Do not use as a general list. |
ConcurrentLinkedQueue / LinkedBlockingQueue | Work queues | Blocking variants for producers/consumers. See Concurrency. |
ConcurrentSkipListMap | Concurrent sorted map | When you need order + concurrency. |
Hashtable and Vector are legacy synchronized types. Do not introduce them.
List.of result — UOE at runtime, often in a rare branch.list.toArray() returns Object[]. Use the typed overload.List.copyOf for snapshots.removeIf.~ Good luck with your revision! ~