- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
Java 8 引入了获取并发 Set
实现的新方法
// Pre-Java-8 way to create a concurrent set
Set<String> oldStyle = Collections.newSetFromMap(new ConcurrentHashMap<>());
// New method in Java 8
Set<String> newStyle = ConcurrentHashMap.newKeySet();
有什么理由更喜欢新方法吗?
有什么优点/缺点吗?
最佳答案
ConcurrentHashMap.newKeySet()
只是比 Collections.newSetFromMap(new ConcurrentHashMap<>())
更广泛的功能的一部分.
如果您看一下这个例子,区别就会变得很明显:
Set<String> set=new ConcurrentHashMap<String,String>().keySet("hello");
而不是映射到 Boolean.TRUE
您现在正在添加值 "hello"
当向 Set
添加新值时.
这就是返回 Set
的原因s 的类型是 ConcurrentHashMap.KeySetView
.这种类型有额外的方法 asking for the backing map以及which value will be used when adding new keys .
所以 ConcurrentHashMap.newKeySet()
看起来和 Collections.newSetFromMap(new ConcurrentHashMap<>())
一样,存在语义差异,后者表示您之后不应该使用 map ,而前者是旨在与 map 交互的功能的一部分。
参见 Collections.newSetFromMap
:
The specified map must be empty at the time this method is invoked, and should not be accessed directly after this method returns.
事实上,甚至没有指定 Collections.newSetFromMap
将使用 Boolean.TRUE
对于附加值——无论如何你都不应该处理它……
当你想通过 Set
时它也可能有用明确请求 ConcurrentHashMap.KeySetView
的代码.
如果您使用编译时类型 Set
的结果只是,仍然有可能接收到 Set
的代码将使用 instanceof
/type 转换以找出 ConcurrentHashMap.newKeySet()
的结果由 ConcurrentHashMap
支持而 Collections.newSetFromMap
的结果不会告诉你。另一方面,这也允许代码以这种方式使用 backing map 做一些意想不到的事情……
关于java - ConcurrentHashMap.newKeySet() 与 Collections.newSetFromMap(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054517/
Java 8 引入了获取并发 Set 实现的新方法 // Pre-Java-8 way to create a concurrent set Set oldStyle = Collections.ne
我正在尝试在 AGP 中使用新的脱糖功能,但是在尝试使用 ConcurrentHashMap.newKeySet() 时出现以下错误在我的应用程序中: 10-23 21:17:49.471 5023-
我是一名优秀的程序员,十分优秀!