Clone(): Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
“clone”creates and returns a copy of the object. It makes another object of the class in memory. Suppose, We are creating a clone of the object x then x.clone() != x will return true but it is not necessary that x.clone().equals(x) will return true. It depends upon the implementation of class.Class should implement “Cloneable” interface in order to make clone of its objects. Otherwise “CloneNotSupportedException” will be thrown.
Array,HashMap are considered to have implemented the interface “Cloneable”. If by assignment, the contents of the fields of class are not themselves cloned then this method performs shallow copy of this object, not a deep copy operation.
Let's pretend that we can peer deep inside the JVM and actually see thememory locations themselves that are the references. I'll put the memory locations of each object in parentheses.
If we have a hashmap, it might contain 3 K/V pairs:
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)
If you assign hashmap2 = hashmap1, then you have two references to the samehashmap object. That means that if you were to peer inside hashmap2, youare looking at the exact same hashmap object. Note that using this example,both references point to location 1000:
hashmap2 = hashmap1
-----------------------------------------
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)
hashmap2(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)
If you do a shallow clone of hashmap1 instead, you will have two hashmapobjects, but with all the same keys and values:
hashmap2 = (Hashmap)hashmap1.clone();
-----------------------------------------
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)
hashmap2(3000) <-----note-----
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)
If you were able to do a deep(er) clone (using your own technique) you mightend up two objects, with copies of all the keys and values:
hashmap2 = magicDeepCloneMethod(hashmap1);
-----------------------------------------
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)
hashmap2(3000)
keyA(4000)---valueA(4010)
keyB(4020)---valueB(4030)
keyC(4040)---valueC(4050)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment