gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:10 26 4
gpt4 key购买 nike

根据 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com