Java 9 provides as a way to create Empty immutable List, set and Map.
List list = List.of();
Set set = Set.of();
Map map = Map.of();
But
Just imagine a regular mathematical operation that is supposed to operate on those collections. Like computing the intersection of lists. The result can be empty, in this case this method would be of good use if the result should be immutable.
public List intersectLists(List first, List second) {
// If one is empty, return empty list
if (first.isEmpty() || second.isEmpty()) {
// Before Java 9: return Collections.emptyList();
return List.of();
}
// Compute intersection
...
}
Immutable collections are often used when you expose internal data structures through getters but don't want the caller to be able to manipulate the collection.
A similar variant are unmodifiable collections. Those can be manipulated, if you have a direct reference to the mutable collection lying underneath the wrapper. By that you can force a user to use your designated methods for manipulation.
public Graph {
private List nodes;
// Other stuff
...
public List getNodes() {
// Wrap container to make list unmodifiable
return Collections.unmodifiableList(nodes);
}
// User should use designated methods to manipulate instead
public void addNode(Node node) { ... }
public void removeNode(Node node) { ... }
}