![](/img/trans.png)
[英]Java - convert unmodifiable sets in a map(key, set) to modifaible
[英]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.