Java Collections
Collections Overview
Complete lesson for Collections Overview using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Collections Overview
Section: Java Collections. The java.util collection hierarchy: List, Set, Queue, Map, complexity, and fail-fast iterators.
The two roots
Collectionis the root of lists, sets, and queues.Mapis a separate hierarchy (key-value, not a Collection).Iterablelets you use for-each.Iteratoris the cursor (hasNext/next/remove).- Program to interfaces: declare
List,Set,Map,Deque— constructArrayList,HashSet,HashMap,ArrayDeque.
| Interface | Duplicates | Order | Common impls |
|---|---|---|---|
List | Yes | Insertion (positional) | ArrayList, LinkedList |
Set | No | Depends | HashSet, LinkedHashSet, TreeSet |
Queue / Deque | Yes | FIFO / both ends | ArrayDeque, LinkedList, PriorityQueue |
Map | Unique keys | Depends | HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap |
Complexity cheat sheet (amortized / average)
| Type | get / contains | add | Notes |
|---|---|---|---|
ArrayList | get O(1); contains O(n) | amortized O(1) at end | RandomAccess; slow mid insert |
LinkedList | get O(n) | O(1) at ends | Node overhead; implements Deque |
HashSet / HashMap | average O(1) | average O(1) | Needs equals/hashCode; no order |
TreeSet / TreeMap | O(log n) | O(log n) | Sorted; Comparable or Comparator |
ArrayDeque | N/A | O(1) at ends | Best default Stack/Queue |
PriorityQueue | peek O(1) | offer O(log n) | Heap; not a sorted list |
Fail-fast vs fail-safe
- Most
java.utiliterators are **fail-fast**: if the collection is structurally modified except viaIterator.remove, they throwConcurrentModificationException. - This is *best-effort*, even on a single thread — a for-each plus
list.addis enough. ConcurrentHashMapiterators are weakly consistent (no CME for concurrent writes).CopyOnWriteArrayListsnapshots on iterate.
import java.util.ArrayList;
import java.util.List;
public class CollectionsOverview {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("ada");
names.add("linus");
for (String n : names) {
System.out.println(n);
}
System.out.println(names.size());
}
} Advanced — Collections Overview
Contracts and interview mistakes
hashCode/equalsmust be consistent orHashSet/HashMaplose keys. Mutable keys are a famous bug.Comparablenatural order must be consistent withequalsforTreeSet/TreeMapor you get “duplicate” keys thatequalssays are equal.- The Collections Framework is not thread-safe by default. Wrap with
Collections.synchronizedListor use concurrent types. null:HashMapallows one null key;ConcurrentHashMap,Hashtable, andTreeMap(with natural order) do not.
Tricky Interview Points
Q1) Is Map a Collection?
Answer No. Map is a separate interface. You can view keys/values/entries as collections via keySet, values, entrySet.
Q2) List vs Set?
Answer List is ordered and allows duplicates and index access. Set forbids duplicates (by equals/hashCode or compare) and has no index.
Q3) What is fail-fast?
Answer An iterator that detects structural modification (via a modCount) and throws ConcurrentModificationException. It is not a reliable concurrency mechanism.
Q4) Why declare List instead of ArrayList?
Answer You can swap implementations (ArrayList vs LinkedList vs unmodifiable List.of) without changing callers.
Q5) Which collection is sorted?
Answer TreeSet and TreeMap (red-black tree). LinkedHashSet/Map keep insertion order but are not sorted by value.
Q6) How do you iterate a Map?
Answer for (var e : map.entrySet()), forEach, or keySet/values. Prefer entrySet to avoid extra lookups.
Simple Programs
Pick a collection by need
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ChooseCollection {
public static void main(String[] args) {
List<String> tickets = new ArrayList<>();
tickets.add("T1");
tickets.add("T1");
Set<String> unique = new HashSet<>(tickets);
Map<String, Integer> freq = new HashMap<>();
for (String t : tickets) {
freq.merge(t, 1, Integer::sum);
}
System.out.println(unique);
System.out.println(freq);
}
} Problem Solving Tricks
List.of/Set.of/Map.of(Java 9+) are unmodifiable and rejectnull.- Need both uniqueness and insertion order?
LinkedHashSet/LinkedHashMap. - Need thread safety and a map?
ConcurrentHashMap, not a synchronizedHashMap, for most cases. - Measure before switching
ArrayListtoLinkedList—LinkedListis almost never faster in real JVMs.
Practice Programs List
- Store names in a List, unique names in a Set, and counts in a Map — same input.
- Trigger
ConcurrentModificationExceptionby adding inside for-each, then fix with an Iterator orremoveIf. - Write a method that accepts
Collectionand works for both List and Set. - Compare
HashSetvsTreeSetiteration order on the same integers. - Explain from memory which implementations allow
null.