What is the Java Collections Framework?
Solution and explanation
What it is
The Java Collections Framework (JCF, java.util) is a unified set of **interfaces**, **implementations** and **algorithms** for storing and processing groups of objects. Code is written against interfaces (List, Map) so implementations can be swapped without changing the rest of the program.
Hierarchy
Iterable
└─ Collection
├─ List (ordered, duplicates, index access) ArrayList, LinkedList, CopyOnWriteArrayList
├─ Set (no duplicates) HashSet, LinkedHashSet, TreeSet
└─ Queue (processing order) ArrayDeque, PriorityQueue, LinkedList
└─ Deque (both ends) ArrayDeque, LinkedList
Map (key → value, not a Collection) HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap
Choosing an implementation
| Need | Use | Key operations |
|---|---|---|
| list with fast index access | ArrayList | get O(1), add at end amortised O(1) |
| unique items, fast lookup | HashSet | add/contains O(1) average |
| unique items, insertion order | LinkedHashSet | O(1) |
| sorted unique items | TreeSet | O(log n), red-black tree |
| key-value lookup | HashMap | get/put O(1) average |
| sorted keys, range queries | TreeMap | O(log n), floorKey, subMap |
| LRU cache | LinkedHashMap with access order | O(1) |
| stack or queue | ArrayDeque | push/pop/offer/poll O(1) |
| always take the smallest/highest priority | PriorityQueue | offer/poll O(log n) |
| shared between threads | ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue |
Algorithms in Collections
List<Integer> scores = new ArrayList<>(List.of(70, 95, 82));
Collections.sort(scores);
Collections.reverse(scores);
Collections.max(scores);
Collections.unmodifiableList(scores);
Collections.frequency(scores, 82);
Why it matters
- Program to interfaces:
List<Job> jobs = new ArrayList<>();. - Generics give compile-time type safety.
- Iterators are **fail-fast**: modifying a collection while iterating throws
ConcurrentModificationException(useIterator.removeorremoveIf).
Summary
The JCF provides interfaces (List, Set, Queue, Map), ready implementations with known complexity, and utility algorithms; choose the implementation from your access pattern.
