HashMap中克隆方法的输出

时间:2017-05-12 16:51:12

标签: java hashmap clone

     // Creating a new HashMap
     HashMap<Integer, String> hmap2 = new HashMap<Integer, String>(); 

     // cloning first HashMap in the second one
     hmap2=(HashMap)hmap.clone();
     //System.out.println("Cloned Map contains: "+hmap2); 
     String x = hmap.get(11);
     x = "aks";
     hmap.put(11, x);
     hmap.put(99, "kdkshkjshdk");

     System.out.println("Cloned Map contains: "+hmap); 
     System.out.println("Cloned Map contains: "+hmap2); 
  } 
}

为什么hmap中的更改没有在hmap2中重新连接?这是一个浅拷贝,hmap和hmap2都指向相同的内存引用。 请纠正我出错的地方。

1 个答案:

答案 0 :(得分:1)

您正在将空hmap克隆到hmap2,然后将值设置为hmap。

     // Creating a new HashMap

     HashMap<Integer, String> hmap = new HashMap<Integer, String>();

     HashMap<Integer, String> hmap2 = new HashMap<Integer, String>();

   //System.out.println("Cloned Map contains: "+hmap2); 

     String x = hmap.get(11);

     x = "aks";

     hmap.put(11, x);

     hmap.put(99, "kdkshkjshdk");

     // cloning first HashMap in the second one

     hmap2=(HashMap)hmap.clone();



     System.out.println("Cloned Map contains: "+hmap); 
     System.out.println("Cloned Map contains: "+hmap2);