Link to home
Start Free TrialLog in
Avatar of shepp_it
shepp_it

asked on

Copying non-primitive data type variable

Hi, I have a HashMap copied from another HashMap, but I want to change the values only in one of them.

For example...
HashMap hm1 = new HashMap();
hm1.put("fruit", "apple");

HashMap hm2 = new HashMap();
hm2 = hm1;
hm1.put("fruit", "orange");
...

Now both hm1 and hm2 has "orange" under fruit key, but I want only hm1 updated. Is a deep copy the only solution?

Thanks in advance.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

A deep copy is the safest solution. btw, you example doesn't show a copy (hm1 == hm2)
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
clone() is worth trying, but if (unlike in your example) you have complex, non-primitive objects in the Map, then they might not be copied deeply enough
Avatar of stachenov
stachenov

In this case you're lucky because HashMap has a copy constructor just for that. This should work and make your code even simpler:

HashMap hm1 = new HashMap();
hm1.put("fruit", "apple");

HashMap hm2 = new HashMap(hm1);
hm1.put("fruit", "orange");

Open in new window

Oh, and there should be "hm2.put" at the last line - I copied it from your code without testing.
And clone() is also working at least for strings in HashMap

        HashMap mm1 = new HashMap();
        mm1.put("fruit","apple");
        mm1.put("vegetable","potato");

        HashMap mm2 = (HashMap)mm1.clone();

        mm2.put("vegetable","tomato");

        System.out.println("mm1: " + mm1);

         System.out.println("mm2: " + mm2);

Open in new window



mm1: {fruit=apple, vegetable=potato}
mm2: {fruit=apple, vegetable=tomato}

Open in new window

>>I think clone() is really implenmented for Hashtable - so you may try using this method.

The implications of clone have little to do with the type on which it's called in this case. The important point is the type of objects in the Map. As i mentioned, clone cannot be considered safe