Lesson · Collections Framework
The Collections toolbox
14 min readCollections Utility Class
The Collections class is a workbench of static tools: ordering, searching, counting, and the wrappers that freeze, synchronise or police another collection. Most missing methods are already in here.
The methods you keep writing yourself
Two tasks that feel custom until you find them in the toolbox: counting how often a value appears, and rotating a list by a few places.
System.out.println(Collections.frequency(votes, "red")); // 3 Collections.rotate(data, 1); // shift right by one
Predict: where would a rotate method live if you had to design the JDK? It cannot be on the List interface, because it is an algorithm, not a promise. It lives on Collections: a grab bag of static algorithms over collection types.
Ordering tools
Everything that rearranges elements in place, in one place:
| Call | Does | Notes |
|---|---|---|
Collections.sort(list) | sorts by natural order | same as list.sort(null) since Java 8 |
Collections.reverse(list) | flips the current order | in place, O(n) |
Collections.shuffle(list) | randomises the order | pass a seeded Random for reproducible runs |
Collections.rotate(list, n) | shifts elements by n places, wrapping | cost is O(n) regardless of distance |
Collections.swap(list, i, j) | exchanges two positions | what sorting internals use |
Collections.min(list) / max(list) | returns the extreme element | uses compareTo, or a comparator |
All of these mutate the list they are given. The methods return void because the change happens inside the argument, which is worth double checking in code review.
Toolbox bench · one list, six tools
pick a toolNatural order of the elements. The list itself changes; nothing is returned.
The wrapper shelf
The expression line for the selected tool: Collections.sort(data);
Searching and counting
The methods that answer where things are and how often they appear:
Collections.binarySearch(list, key)returns the index, if and only if the list is sorted in the same order first. A wrong order yields wrong answers, not errors.Collections.frequency(collection, value)counts occurrences in one pass; hand-rolling the loop is a sign the toolbox is unknown.Collections.disjoint(a, b)answers whether two collections share no elements at all.Collections.addAll(collection, items...)bulk-adds and returns whether anything changed.
Sort, then search, with the same order. Binary search is the one tool in the box that trusts something you did earlier, so it is the one that can fail silently.
The wrappers
Three decorator families that layer behaviour over an existing collection:
| Wrapper | Adds | Price |
|---|---|---|
unmodifiableList / Set / Map | write methods throw UnsupportedOperationException | a view: changes through the original still show |
synchronizedList / Set / Map | each call locks the wrapper | compound actions (check then set) still need your own synchronized block |
checkedList / Set / Map | rejects wrong-typed insertions at the boundary | guards against raw-type leaks, not a type system |
- `emptyList()`, `singletonList(x)`, `nCopies(n, x)` return immutable, allocation-light lists.
emptyList()even reuses one shared instance. - Wrappers compose: an unmodifiable view over a synchronized list is a legitimate pattern, and each wrapper adds one more layer on every call.
- Wrappers are not copies. Freeze a snapshot with
List.copyOfwhen the data must not follow its source.
Collection versus Collections
One letter separates the interface from the toolbox, and interviewers ask exactly this:
- `Collection` is the interface: the shared contract of lists, sets and queues.
- `Collections` is a final utility class of static methods: algorithms, wrappers and empty singletons.
- The same pattern repeats across java.util:
Objectsfor object helpers,Arraysfor array helpers,Filesfor file helpers.
Missing method? Check the toolbox first. sorting, searching, counting, rotating, freezing and locking all live on Collections, not on the types themselves.
The toolbox playbook
Reaching into Collections, in order:
- Reordering, counting, testing overlap: try Collections before writing a loop.
- Binary search only after a sort with the identical order; otherwise use a plain scan or a Set.
- Freezing for safety of reading:
unmodifiable; freezing a snapshot the caller cannot follow:copyOf. - Sharing across threads:
synchronizedwrapper plus manual locking for anything multi-step, or switch to the concurrent collections. - Remember the plural: the interface is Collection, the toolbox is Collections.
A workbench, not a type. Nothing here changes what your collections are, only what algorithms and guards sit on top of them.
Algorithms and guards live on Collections, not on the types
sort, reverse, shuffle, rotate, swap, min, max, frequency, disjoint and binarySearch are static methods on the Collections class, and so are the wrappers: unmodifiable, synchronized and checked. The wrappers decorate without copying, which is why an unmodifiable view still follows its source while List.copyOf does not. One letter apart from the Collection interface, and entirely different jobs.
Interview angles
Why are sort and friends on Collections and not on List?+
Because they are algorithms over the contract, not promises of the type. Putting them on the interface would freeze one implementation strategy into every List ever written.
The split is deliberate: Collection and List say what the container guarantees; Collections supplies the operations built on those guarantees. Since Java 8 a few favourites moved onto the interfaces as default methods (list.sort, forEach, removeIf), which is the modern trend, but the toolbox still owns the long tail.
Common misconception: That Collections.sort is gone or deprecated. It is still the canonical call, now delegated to List.sort.
Follow-up: Which toolbox method trusts a decision you made earlier?
How does binarySearch fail, and why silently?+
It prunes half the remaining range on every probe, trusting that the list is sorted in the exact order you are searching with. If it is not, entries are simply never found, with no exception.
The same rule covers comparators: sort with comparing(...).thenComparing(...) and search with the identical comparator. Any difference, including tie-breaking or null policy, breaks the trust relationship.
Common misconception: That binarySearch detects a wrong order and falls back. It does not detect anything; it returns wrong indices.
Follow-up: What is the complexity difference against a plain contains scan?
unmodifiableList versus List.copyOf: what is the difference?+
unmodifiableList is a view: writes throw, but the view follows changes made through the original list. copyOf is a snapshot: a new, frozen list that no one can change afterwards.
Both reject writes with UnsupportedOperationException. The difference only shows when someone keeps a handle to the source. For safety you hand to callers, copyOf is usually what you mean; for a live read-only window over your own data, the view is cheaper.
Common misconception: That unmodifiable means the data cannot change. It means it cannot change through this reference.
Follow-up: Where does that bite in real code?
What does a synchronized wrapper actually synchronise?+
Each individual method call locks the wrapper, so single operations are safe across threads. Anything multi-step, like check-then-put or iterating, still needs your own synchronized block on the same lock.
That is why the concurrent collections exist: ConcurrentHashMap and friends make compound operations atomic and iterators safe, while the wrapper only makes single calls atomic. A forgotten lock around iteration throws ConcurrentModificationException even with the wrapper in place.
Common misconception: That wrapping in synchronizedList makes all code touching the list safe. It makes each call safe, which is not the same sentence.
Follow-up: When is the wrapper still the right choice?
Name a few singletons and why they exist.+
emptyList, emptySet, emptyMap, singletonList, singleton, nCopies: immutable helpers that avoid creating a new object for every empty or single-element result.
They are safe to share freely because they cannot change, and emptyList always returns the same instance. Together with List.of and Map.of they form the standard vocabulary for returning fixed data from APIs without allocating on every call.
Common misconception: That returning emptyList is different from returning a new ArrayList. It is the same usable empty list, minus the allocation and plus the write protection.
Follow-up: What happens if a caller tries to add to it?