Collections Framework
The Collections Framework
One interface hierarchy —
Collection branching into List, Set, and Queue, with Map alongside — and interchangeable implementations behind it. Program to the interface; choose the implementation for its performance shape.- Core interfaces:
Collection,List,Set,SortedSet/NavigableSet,Queue,Deque,Map - Declare variables as the interface type:
List<String> l = new ArrayList<>()(EJ 64) — swap the implementation later without touching a single caller Iterablepowers for-each;Iterator.removeis the only safe removal during iteration- Factory methods
List.of/Set.of/Map.ofcreate compact immutable collections - Optional operations: immutable views throw
UnsupportedOperationExceptionon mutation
| Interface | Hash-based | Array-based | Tree-based | Linked |
|---|---|---|---|---|
List | — | ArrayList ✦ | — | LinkedList |
Set | HashSet ✦ | — | TreeSet | LinkedHashSet |
Map | HashMap ✦ | — | TreeMap | LinkedHashMap |
Queue | — | ArrayDeque ✦, PriorityQueue | — | LinkedList |
✦ = the default choice. The framework's design bet: a small set of interfaces, each with a handful of implementations distinguished only by performance characteristics and iteration order. Algorithms (Collections.sort, binarySearch, shuffle) are written once against the interfaces.
List<String> wordList = new ArrayList<>(); // swap to LinkedList without touching callers
Set<Integer> seen = new HashSet<>();
Map<String, List<Order>> byCustomer = new HashMap<>();
List<String> fixed = List.of("S", "M", "L"); // immutable, null-hostile, compactList.of/Map.of collections reject null and are truly immutable — unlike Arrays.asList (fixed-size but write-through, Arrays) and unlike Collections.unmodifiableList (a read-only view of a possibly-changing list, Views Algorithms).