繁体   English   中英

当retainall用于java中的两个键集时,不可修改的集合问题

[英]unmodifiable collection issue when retainall is used for two key sets in java

Map<String,String> map=request.getParameterMap();

^是不可修改的地图。

Set s1= map.keySet();
Set s2= map2.keySet();/* another keyset of local map*/

使用s1.retainAll(s2)抛出异常: at java.util.collections$unmodifiablecollection.retainall

这里request.getParameterMap()返回一个不可修改的地图..我尝试创建一个本地地图。 但问题仍然存在。 建议一些解决方案。

Set.retainAll方法修改它被调用的集合。 假设你不可修改的map的keySet方法只是对底层映射的一个视图,它不应该允许修改。 您可能想要创建一个新的(可修改的)集合,然后从中删除项目:

Set s1 = new HashSet(map.keySet());
s1.retainAll(s3);

您不能修改不可修改映射的键集,因为返回的键集也是不可修改的Set。 您可以从unmodifiableMap创建本地映射,而不是在本地映射键集上使用retainAll。

Map map1 = new HashMap();
map1 = Collections.unmodifiableMap(map1);
Map map2 = new HashMap();
Map map3 = new HashMap(map1);
Set s1 = map1.keySet();
Set s2 = map2.keySet();
Set s3 = map3.keySet();
s3.retainAll(s2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM