3

我想计算两个哈希图的键的并集。我写了以下代码(下面是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);


    }


}
4

3 回答 3

7

所以,union不是副本one one first.keySet()。并且first.keySet()不是 的键的副本first它是一个视图,并且不支持添加,如Map.keySet().

所以你需要实际做一个副本。最简单的方法可能是写

 one = new HashSet<String>(first);

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

于 2013-02-15T00:29:42.517 回答
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);
于 2013-02-15T00:31:32.447 回答
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());


    }


}
于 2013-02-15T00:31:23.673 回答