java - Java 10 中的 Collectors.toUnmodifiableList 与 Collections.unmodifiableList

标签 java java-8 java-10

根据 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 及更高版本中拥有真正的不可变列表。有两种方法可以获取真正不可修改的列表,如下所示:

  1. var unmodifiableList = List.copyOf(srcList); => 打印 Apple
  2. var unmodifiableList = srcList.stream().collect(Collectors.toUnmodifiableList()); => 打印 Apple

所以 Collectors.toUnmodifiableList 方法返回一个真正的不可修改列表 List.of 在 Java 9 中引入。这个方法返回一个 Collector 其中Collections.unmodifiableList 方法返回一个列表。根据 doc不可修改列表具有以下特点:

  1. 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.
  2. They disallow null elements. Attempts to create them with null elements result in NullPointerException.
  3. They are serializable if all elements are serializable.
  4. 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.
  5. 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.
  6. They are serialized as specified on the Serialized Form page.

关于java - Java 10 中的 Collectors.toUnmodifiableList 与 Collections.unmodifiableList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620446/

相关文章:

.map 返回的 Java-8 Stream 是并行的还是顺序的?

cassandra - Cassandra 是否支持 Java 10?

java - Android Studio 中的 Maven 是什么?

java - 匹配具有特定扩展名的所有文件名,特定文件名正则表达式除外

java - Perforce Java API 行结束样式

java - JAXB 解码到具体类而不使用 xsi :type in xml but using actual concrete class name

Java8 Stream .orElseThrow 未报告的异常错误

java - 如何在 Java 中实现谓词,用于根据任意数量的规则交叉检查字符串?

Java 10 JavaFX java.lang.IllegalAccessError

java - Java 9+ 中滚动嵌套表时的重画问题