gpt4 book ai didi

java - List#copyOf、Set#copyOf 和 Map#copyOf 与传统方法有什么区别?

转载 作者:搜寻专家 更新时间:2023-11-01 01:40:11 25 4
gpt4 key购买 nike

Java 10 的发布带来了新的静态工厂方法,具体来说:

因为这些方法允许我们复制 Collection s 不同 Collection实现,它们如何与现有方法进行比较和对比?

最佳答案

正如 List#of , Set#of , 和 Map#ofEntries 允许我们在 Java 9 中创建不可修改 实现,copyOf方法提供了一种从现有 Collection 创建不可修改 实现的便捷方式s 和 Map s(取决于方法,因为 Map#copyOf 接受 Map )在 Java 10 中。

这使我们能够轻松地创建一个不可修改 Set<E>来自List<E>反之亦然。

不过,这些方法带来了一些注意事项(引用 java.util.Listdocumentation):

  • 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.

关于 Set#copyOf 的注意事项和 Map#copyOf ,请参阅他们的文档。

关于java - List#copyOf、Set#copyOf 和 Map#copyOf 与传统方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49089751/

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