【问题标题】:Computing the union of the keySets of two HashMaps in Java在 Java 中计算两个 HashMap 的 keySet 的并集
【发布时间】:2013-02-15 00:26:30
【问题描述】:

我想计算两个哈希映射的键的并集。我写了以下代码(下面是MWE),但是我

得到 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);


    }


}

【问题讨论】:

    标签: java hashmap set


    【解决方案1】:

    所以,union 不是one副本,它 onefirst.keySet()。并且first.keySet() 不是firstit's a view, and won't support adds 的密钥的副本,如Map.keySet() 中所述。

    所以你实际上需要做一个副本。最简单的方法大概就是写

     one = new HashSet<String>(first);
    

    它使用HashSet 的“复制构造函数”来进行实际复制,而不是仅仅引用同一个对象。

    【讨论】:

      【解决方案2】:

      请记住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);
      

      【讨论】:

        【解决方案3】:

        改用下面的代码

        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());
        
        
            }
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-25
          • 2011-11-26
          • 2017-09-19
          • 1970-01-01
          • 1970-01-01
          • 2012-07-18
          相关资源
          最近更新 更多