编程语言
首页 > 编程语言> > java – 传统方法中List#copyOf,Set#copyOf和Map#copyOf的区别是什么?

java – 传统方法中List#copyOf,Set#copyOf和Map#copyOf的区别是什么?

作者:互联网

Java 10的发布带来了新的静态工厂方法,特别是:

> static <E> List<E> copyOf​(Collection<? extends E> coll)
> static <E> Set<E> copyOf​(Collection<? extends E> coll)
> static <K,V> Map<K,V> copyOf​(Map<? extends K,? extends V> map)

看作这些方法允许我们将集合复制到不同的集合实现中,它们如何与现有方法进行比较和对比?

解决方法:

正如List#of,Set#ofMap#ofEntries允许我们在Java 9中创建不可修改的实现一样,copyOf方法提供了一种方便的方法来从Java中创建现有集合和映射(取决于方法,如Map#copyOf接受Map)的不可修改的实现10.

这允许我们容易地创建不可修改的Set< E>.从列表< E>反之亦然.

但是,这些方法带来了一些警告(引用java.util.List的documentation):

  • 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-10,java,collections,factory-method
来源: https://codeday.me/bug/20190727/1550185.html