根据 doc Collections.unmodifiableList
方法返回指定列表的不可修改 View 。返回的列表真的不可修改吗?不可修改的 View 是什么意思?
根据 doc Collectors.toUnmodifiableList
方法返回一个收集器,该收集器按遇到的顺序将输入元素累积到一个不可修改的列表中。这里返回的列表真的是不可修改的吗?
注意:我所说的可修改是指可以使用set
操作修改 View 。我想了解其中的区别以及它们之间的关系?
最佳答案
Collections.unmodifiableList
方法返回指定列表的不可修改 View 。不可修改的 View 集合是不可修改的集合,也是支持集合的 View 。请注意,对支持集合的更改可能仍然是
可能,如果发生,它们通过不可修改的 View 是可见的。
List<String> srcList = Arrays.asList("Apple", "Banana", "Cherry");
var fruits = new ArrayList<>(srcList);
var unmodifiableList = Collections.unmodifiableList(fruits);
fruits.set(0, "Apricot");
var modFruit = unmodifiableList.get(0);
System.out.println(modFruit); // prints Apricot
我们可以在 Java 10 及更高版本中拥有真正的不可变列表。有两种方法可以获取真正不可修改的列表,如下所示:
var unmodifiableList = List.copyOf(srcList);
=> 打印 Applevar unmodifiableList = srcList.stream().collect(Collectors.toUnmodifiableList());
=> 打印 Apple
所以 Collectors.toUnmodifiableList
方法返回一个真正的不可修改列表 List.of
在 Java 9 中引入。这个方法返回一个 Collector
其中Collections.unmodifiableList
方法返回一个列表。根据 doc不可修改列表具有以下特点:
- They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change.- They disallow null elements. Attempts to create them with null elements result in
NullPointerException
.- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
- They are
value-based
. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances (reference equality (==), identity hash code, and synchronization) are unreliable and should be avoided.- They are serialized as specified on the Serialized Form page.
关于java - Java 10 中的 Collectors.toUnmodifiableList 与 Collections.unmodifiableList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620446/