Stop 08 · Collections & GenericsTopics · 10/10

Immutable Collections & the Collections Utility Class

Part of the Java Roadmap

In short

A list that nobody can change by accident is a list you never have to debug. Java makes those in one line, and the Collections class gives you sorting, shuffling and counting helpers for free.

List.of, Set.of and Map.of create unmodifiable collections, and Collections offers helpers like sort, reverse, shuffle, max, frequency and unmodifiableList. Immutable collections are safer to share between classes and threads.

The jaadu proudly holds up a shiny laminated menu card while a customer's pen slides off its surface without leaving a mark.

Think of it like this

A laminated menu card

A restaurant's laminated menu can be read by every customer, but nobody can scribble a new dish onto it. List.of gives you that laminated card. Collections.unmodifiableList is more like a glass case over the kitchen whiteboard: you cannot write on it, but the chef behind the glass still can.

Watch it happen

Frozen copy vs read-only view

List.of / List.copyOf

  • Truly unmodifiable, its own data
  • add, remove, set throw UnsupportedOperationException
  • No null elements allowed
  • Never changes once created

Collections.unmodifiableList

  • A read-only view of another list
  • Writes through the view throw
  • Changes to the original list show through
  • Good for exposing internal lists safely

Want a snapshot nobody can change? List.copyOf. Want to hand out a read-only window onto live data? unmodifiableList.

The big ideas

What you need to know

Factory methods

List.of, Set.of and Map.of build small unmodifiable collections in one line. Map.of takes up to 10 pairs.

Safe to share

Immutable collections can be passed between classes and threads without anyone changing them under you.

Collections helpers

sort, reverse, shuffle, max, min, frequency, nCopies and swap save you from writing loops.

Rules to remember

List.of rejects nulls, Set.of and Map.of reject duplicate elements or keys with IllegalArgumentException.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.Collections;3import java.util.List;4import java.util.Map;5 6public class ImmutableDemo {7    public static void main(String[] args) {8        List<String> metros = List.of("Delhi", "Mumbai", "Chennai");9        // metros.add("Pune");  // UnsupportedOperationException at runtime10 11        Map<String, Integer> fares = Map.of("AC", 1200, "Sleeper", 450);12 13        List<Integer> marks = new ArrayList<>(List.of(78, 91, 64, 91, 85));14        Collections.sort(marks);                               // [64, 78, 85, 91, 91]15        Collections.reverse(marks);                            // [91, 91, 85, 78, 64]16        System.out.println(Collections.max(marks));            // 9117        System.out.println(Collections.frequency(marks, 91));  // 218 19        List<Integer> view = Collections.unmodifiableList(marks);20        marks.add(50);21        System.out.println(view.size());                       // 6: the view sees the change22 23        List<Integer> snapshot = List.copyOf(marks);           // a true frozen copy24        System.out.println(metros + " " + snapshot.size() + " " + fares.get("AC"));25    }26}

1/4List.of and Map.of build fixed collections. Any attempt to change them fails at runtime.

Immutable factories for fixed data, the Collections helpers on a mutable list, and the difference between a view and a copy.

Save yourself the pain

Common mistakes

Oops

Returning your private ArrayList directly from a getter.

Do this instead

Return List.copyOf(items) or Collections.unmodifiableList(items) so callers cannot change your object's state.

Oops

Calling Arrays.asList(...).add(x).

Do this instead

Arrays.asList is fixed-size. Wrap it: new ArrayList<>(Arrays.asList(...)) when you need to add.

Oops

Putting null into List.of(...).

Do this instead

Immutable factories reject null with NullPointerException. Filter out nulls first.

Your mission

Lock down a class

~25 min

Quick check

You wrap a list with Collections.unmodifiableList and then add to the original list. What does the view show?

Go deeper

  1. 1Create a List.of and try to add to it to see the exception.
  2. 2Sort, reverse and shuffle a list with the Collections class.
  3. 3Return an unmodifiable view from a getter so callers cannot change your object's list.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge