JavaBeginner#collections

How do you make a collection immutable?

Use Collections.unmodifiableList/Set/Map to wrap an existing collection (still reflects changes to the underlying one), or use List.of/Set.of/Map.of (Java 9+) to create truly immutable collections directly.

Example
List<Integer> immutable = List.of(1, 2, 3);
immutable.add(4); // throws UnsupportedOperationException

Related Questions

1
JavaBeginner#collections

What is the difference between Collection and Collections?

Open
2
JavaIntermediate#generics

What is a bounded type parameter in generics?

Open
3
JavaBeginner#generics

Can you use primitive types with generics?

Open