An unmodifiable collection exposes collection operations without permitting callers to change its contents. When its elements are values, it can behave like a value object: equality depends on contained state rather than identity. section 2.2.2
Choose the representation according to the semantic guarantee you want:
- Wrap an existing mutable collection with Collections.unmodifiableList when callers should not modify it through the exposed reference. section 2.2.2
- Use List.of, Set.of, or Map.of when constructing unmodifiable collections directly. section 2.2.2
- Use List.copyOf at a record boundary when the record must not retain a mutable caller-owned list. section 2.6.2
- Expose a dedicated ImmutableList type when List would hide the intended immutability from readers and the type system. section 2.6.2
Making a record’s list safe
record Person(String name, List<String> friends) { Person { friends = List.copyOf(friends); } } List<String> friends = Arrays.asList("Joe", "Jane"); Person person = new Person("Bob", friends); friends.set(0, "Billy"); // person still contains [Joe, Jane] section 2.6.2
Listing 2.42 AI generated immutable versions of the collection API methods
record ImmutableList<A>(List<A> items) {
ImmutableList {
items = List.copyOf(items);
}
// Methods added by AI
public ImmutableList<A> add(A item) { #A
var newItems = new ArrayList<A>(items);
newItems.add(item);
return new ImmutableList<>(newItems);
}
public ImmutableList<A> addAll(List<? extends A> itemsToAdd) { #A
var newItems = new ArrayList<A>(items);
newItems.addAll(itemsToAdd);
return new ImmutableList<>(newItems);
}
// and so on...
}
System.out.println(ImmutableList.of(1,2,3) #B
.add(4) #B
.addAll(ImmutableList.of(5,6,7))); #B
// [out]
// ImmutableList[items=[1,2,3,4,5,6,7]]Shows an ImmutableList whose add and addAll operations return new lists instead of mutating the existing value. section 2.6.2
