Is there any practical application/use case when we create empty immutable list / set / map

前端 未结 3 1276
暗喜
暗喜 2021-01-19 03:28

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

3条回答
  •  离开以前
    2021-01-19 04:14

    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) { ... }
    }
    

提交回复
热议问题