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

前端 未结 3 1310
暗喜
暗喜 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:05

    Whenever a class exposes an internal collection (through a public property, a getter etc) it either has to copy the entire collection or expose an immutable collection, to avoid the caller manipulating internal datastructures.

    For example you could have some list of integers that's used internally but that's also exposed through a getter. Since the list is infrequently updated but often read, you decide to make the internal list immutable (making a new list on each update). That way your getter can just hand a reference to the internal list without copying anything. Now, sooner or later that list will have to be empty, necessitating an empty immutable list.

提交回复
热议问题