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

时间:2012-05-23 04:39:57

标签: java map

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()返回一个不可修改的地图..我尝试创建一个本地地图。但问题仍然存在。 建议一些解决方案。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

由于返回的键集也是不可修改的,因此不允许修改不可修改映射的键集。您可以从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);