Reputation: 21
// 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);
}
}
Why the changes in the hmap are not getting refelcted in hmap2? This is a shallow copy and both hmap and hmap2 are pointing to same memory reference. Please correct where I am going wrong.
Upvotes: 1
Views: 22
Reputation: 44
You are cloning the empty hmap to hmap2 and then setting the values in to 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);
Upvotes: 1