ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-27 04:04:06  阅读:382  来源: 互联网

标签:java-10 java collections factory-method


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有