java - HashMap 中克隆方法的输出

标签 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 中的更改没有反射(reflect)在 hmap2 中?这是一个浅拷贝,hmap 和 hmap2 都指向相同的内存引用。 有错误的地方请指正。

最佳答案

您正在将空 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); 

关于java - HashMap 中克隆方法的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942834/

相关文章:

jquery克隆表单元素并将其插入表单中

mercurial - 如何分支整个存储库,包括忽略文件

java - 如何 "split"在不同 JSON 数组之间映射值?

java - 迭代器的迭代器

java - 如何确定HashMap中方法的最坏情况复杂度?

mongodb - 使用golang从mongodb集合中获取特定的键值对

java - Hashtable 与 Hashmap 有何不同

generics - 如何在不使用克隆的情况下编写保持状态并返回值的通用迭代器?

java - Apache Camel + RabbitMq - Camel 定义了自己的队列,并且不会从已定义的队列中读取

java - 序列化与 Parcelable Android