Java ConcurrentHashMap.newKeySet()与Collections.newSetFromMap()的比较
Java8引入了获取并发Java ConcurrentHashMap.newKeySet()与Collections.newSetFromMap()的比较,java,set,java-8,java.util.concurrent,concurrenthashmap,Java,Set,Java 8,Java.util.concurrent,Concurrenthashmap,Java8引入了获取并发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(); //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();
//Java-8之前创建并发集的方法
Set oldStyle=Collections.newSetFromMap(新的ConcurrentHashMap());
//java8中的新方法
Set newStyle=ConcurrentHashMap.newKeySet();
有什么理由选择新方法吗
有什么优点/缺点吗?
ConcurrentHashMap.newKeySet()
应该更有效,因为它可以删除单一级别的间接寻址Collections.newSetFromMap(map)
主要基于将操作重定向到map.keySet()
,但是ConcurrentHashMap.newKeySet()
非常接近map.keySet()
本身(仅支持添加)
至于功能,我看不出有什么不同。
ConcurrentHashMap.newKeySet()
只是一个功能的一部分,它比Collections.newSetFromMap(new ConcurrentHashMap())要广泛得多。
如果您看一下这个示例,差异就会变得很明显:
Set<String> set=new ConcurrentHashMap<String,String>().keySet("hello");
Set Set=new ConcurrentHashMap().keySet(“hello”);
当向集合添加新值时,您现在正在添加值“hello”
,而不是映射到Boolean.TRUE
这就是返回的Set
s具有该类型的原因。此类型具有用于的其他方法以及
因此,尽管ConcurrentHashMap.newKeySet()
看起来与Collections.newSetFromMap(new ConcurrentHashMap())
的操作相同,但语义上的区别在于后者表示以后不应使用地图,而前者是设计用于与地图交互的功能的一部分
见:
调用此方法时,指定的映射必须为空,并且不应在此方法返回后直接访问
事实上,它甚至没有指定Collections.newSetFromMap
将使用Boolean.TRUE
作为附加值,无论如何,您都不应该处理这个问题
当您想要将Set
传递给显式请求ConcurrentHashMap.KeySetView
的代码时,它可能也很有用
如果仅使用编译时类型Set
来使用结果,则接收该Set
的代码仍有可能使用instanceof
/type强制转换来查找ConcurrentHashMap.newKeySet()的结果
由ConcurrentHashMap
支持,而集合的结果不会告诉您。另一方面,这也允许代码以这种方式使用backing map做一些不希望做的事情…它比较短…虽然这是事实,但我不认为这项功能在ConcurrentHashMap.newKeySet()
…@Tagir Valeev()中有什么用处。我添加了一个注释,应该可以说明这一点。“仅支持修改”意味着可以添加吗?因为键集始终具有删除支持。as删除单个级别的间接寻址
-您确定吗?正如我所见,KeySetView仍然将其方法委托给内部映射。@turbanoff,KeySetView
将其方法委托给映射,但是newSetFromMap
首先将其方法委托给keySet方法,而keySet方法又将其委托给映射。这就是为什么它少了一个间接层。