Immutable collections: List.of, Set.of, Map.of
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Some collections should never change once they are built: the payment methods a store accepts, the products in today's sale, the items of an order that was already placed. Java builds such collections in one line with List.of, Set.of and Map.of. This lesson shows what they promise, what they do not promise, and how to copy a changeable collection into a safe one.
What you will learn
- Create immutable lists, sets and maps with List.of, Set.of and Map.of
- Predict the exceptions: UnsupportedOperationException, NullPointerException and IllegalArgumentException
- Explain why an immutable collection can still show changes inside its objects
- Protect a class with List.copyOf, Set.copyOf and Map.copyOf (a defensive copy)
- Choose between an immutable collection, an unmodifiable view and a copy
Topics in this lesson
- List.of, Set.of and Map.of
- Rules that surprise people
- Immutable is not deep
- Copying: List.copyOf and the defensive copy
- Choosing: immutable, view or copy
Key points
List.of,Set.ofandMap.ofmake immutable collections:add,set,removeandputthrowUnsupportedOperationException.- They reject
null;Set.ofandMap.ofreject repeats withIllegalArgumentException, and their order is not fixed. - Immutable means the collection cannot change, not the objects inside it; make the items immutable too.
List.copyOfis a snapshot (a defensive copy);unmodifiableListis a read-only view that follows the original.
Interview questions this lesson answers
- What is an immutable collection?
- What is the difference between
List.ofandCollections.unmodifiableList? - Are the objects inside
List.of(...)immutable too? - Why does
Set.ofthrow on a repeated item, and why should you not rely on its order? - Can
List.ofholdnull? - What is a defensive copy, and how do you make one with collections?
- When would you choose
List.copyOfoverCollections.unmodifiableList?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.