Search code examples
javahashmapclone

Copy of an hashmap


I have an Hashmap <integer, Arraylist<Double>>. I would like to make a copy of it. I was thinking of using method clone of hashmap. After going through the javadoc, it says the following:

clone
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned. 

What does this shallow copy means? I want a separate matrix , whose values does not change while updating the value of original matrix.

Moreover why does,

    if( hm1 == hm1.clone()) 

returns false?


Solution

  • The shallow copy means that only the map object is created new, but its values are not cloned, i.e. the copy contains references to the old entries. So to "deep clone" a map you would need to do:

    1. create a new hash map object
    2. iterate over all entries in the old map and add the (deep) clones of the key and value to the new map

    Because == compares the object reference, not the content of the map.