2013-02-15 29 views
2

我想計算兩個hashmaps的鍵的聯合。我寫了下面的代碼(下面的MWE),但我用Java計算兩個HashMap的keySet的聯合

得到UnsupportedOperationException。完成這個有什麼好處?

import java.util.HashMap; 
import java.util.Map; 
import java.util.Set; 


public class AddAll { 

    public static void main(String args[]){ 

     Map<String, Integer> first = new HashMap<String, Integer>(); 
     Map<String, Integer> second = new HashMap<String, Integer>(); 

     first.put("First", 1); 
     second.put("Second", 2); 

     Set<String> one = first.keySet(); 
     Set<String> two = second.keySet(); 

     Set<String> union = one; 
     union.addAll(two); 

     System.out.println(union); 


    } 


} 

回答

7

所以,union不是複製的one,它one。它first.keySet()。並且first.keySet()不是first,it's a view, and won't support adds的密鑰的副本,如Map.keySet()中所記錄。

所以你需要真正做一個副本。最簡單的方法可能是寫

one = new HashSet<String>(first); 

它使用的HashSet「複製構造函數」做一個實際的複製,而不是僅僅指的是同一個對象。下面的代碼

+0

謝謝大家的支持數據。這是豐富的,正是我所需要的。 – 2013-02-15 00:34:21

0

改用

import java.util.HashMap; 
import java.util.Map; 
import java.util.Set; 


public class AddAll { 

    public static void main(String args[]){ 

     Map<String, Integer> first = new HashMap<String, Integer>(); 
     Map<String, Integer> second = new HashMap<String, Integer>(); 
     Map<String, Integer> union = new HashMap<String, Integer>(); 
     first.put("First", 1); 
     second.put("Second", 2); 
     union.putAll(first); 
     union.putAll(second); 

     System.out.println(union); 
     System.out.println(union.keySet()); 


    } 


} 
1

記住keySet是地圖的實際數據,它不是一個副本。如果它允許你在那裏打電話addAll,那麼你會將所有這些鍵轉儲到沒有值的第一張地圖上! HashMap故意僅允許您使用實際映射的put類型方法添加新映射。

你想union是一個實際的一套新的可能,而不是第一hashmapL

Set<String> one = first.keySet(); 
    Set<String> two = second.keySet(); 

    Set<String> union = new HashSet<String>(one); 
    union.addAll(two); 
相關問題