如何将一个hashmap内容复制到另一个hashmap

时间:2013-06-27 07:42:34

标签: java hashmap

这里我有两个哈希图datazscreen_dataz。我想将screen_dataz复制到dataz

我正在尝试这样但是它不起作用:

Object[]  obj = new Object[5];
String[] strArray = new String[]{"Obj1","Array1","Converted1","To1","List1"};
String[] strArray1 = new String[]{"Obj2","Array2","Converted2","To2","List2"};
dataz.put(0,(Object[]) strArray);
dataz.put(1,(Object[]) strArray1);
// String dataString = (String) dataz;
System.out.println(dataz);


Object[]  obj1= new Object[5];
String[] strArray2 = new String[]{"Obj3","Array3","Converted3","To3","List3"};
String[] strArray3 = new String[]{"Obj4","Array4","Converted4","To4","List4"};
screen_dataz.put(0,(Object[]) strArray2);
screen_dataz.put(1,(Object[]) strArray3);
System.out.println("copying screen dataz to dataz");
dataz.putAll(screen_dataz);

7 个答案:

答案 0 :(得分:17)

使用构造函数并将其浅化。

dataz = new HashMap<Key,val>(screen_dataz);

答案 1 :(得分:8)

你可以简单construct一个新的:

dataz = new HashMap<Integer,Object>(screen_dataz);

答案 2 :(得分:6)

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

详细explanation

答案 3 :(得分:3)

已发布here

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

答案 4 :(得分:2)

由于您在datazscreen_dataz中使用了相同的密钥(0和1),因此无法正常工作。

根据official javadocputAll&#34;将替换此地图对当前位于指定地图中的任何关键字的所有映射。&#34;,因此您现在正在失去您之前的对象包含在dataz

答案 5 :(得分:1)

试试这个

    HashMap<Integer,String> myMap=new HashMap<>();
    myMap.put(1,"A");
    myMap.put(2,"B");
    HashMap<Integer,String> newMap=new HashMap<>();
    newMap.putAll(myMap);

答案 6 :(得分:0)

HashMap<String, String> hash1 = new HashMap();
    hash1.put("one", "the firs one");
    hash1.put("two", "the second one");
    hash1.put("three", "the third one");
    HashMap<String, String> hash2 = new HashMap<>();
    hash2.putAll(hash1);