简体   繁体   English

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

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

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

^ is the unmodifiable map. ^是不可修改的地图。

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

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

Here request.getParameterMap() returns an unmodifiable map.. I tried creating a local map. 这里request.getParameterMap()返回一个不可修改的地图..我尝试创建一个本地地图。 But the issue stil persists. 但问题仍然存在。 Suggest some solution. 建议一些解决方案。

The Set.retainAll method modifies the set it's being called on. Set.retainAll方法修改它被调用的集合。 Assuming the keySet method of you unmodifiable map is just a view on to the underlying map, it shouldn't allow modifications. 假设你不可修改的map的keySet方法只是对底层映射的一个视图,它不应该允许修改。 You probably want to create a new (modifiable) set and then remove items from it: 您可能想要创建一个新的(可修改的)集合,然后从中删除项目:

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

You are not allowed to modify the keyset of an unmodifiable map as the keyset returned is also unmodifiableSet. 您不能修改不可修改映射的键集,因为返回的键集也是不可修改的Set。 You can create a local map from the unmodifiableMap and than use retainAll on local map keyset. 您可以从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