gpt4 book ai didi

java - ConcurrentHashMap.newKeySet() 与 Collections.newSetFromMap()

转载 作者:搜寻专家 更新时间:2023-10-30 19:41:33 27 4
gpt4 key购买 nike

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/

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