Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create a copy of a Map using pass-by-value?

Tags:

java

copy

map

If I have a Java map with 100s of values in it, and I wanted to create another copy of it using this code :

LinkedHashMap<String, Vector<String>> map1 = new LinkedHashMap<String, Vector<String>>();
LinkedHashMap<String, Vector<String>> map2 = new LinkedHashMap<String, Vector<String>>( map1 );

Then if I change any value in any Vector entry for map1 it will be affected in map2 also. I do not want that. I want map2 to be totally independent on map1.

What is the best way to do that ?

like image 737
Brad Avatar asked Jan 15 '23 14:01

Brad


1 Answers

Basically, you'll need to clone each vector:

LinkedHashMap<String, Vector<String>> map2 = new LinkedHashMap<String, Vector<String>>();
for (Map.Entry<String, Vector<String>> entry : map1.entrySet()) {
    Vector<String> clone = new Vector<String>(entry.getValue());
    map2.put(entry.getKey(), clone);
}

You don't have to go any deeper than that though, of course - because String is immutable.

(Any reason you're using Vector rather than ArrayList, by the way?)

like image 140
Jon Skeet Avatar answered Mar 05 '23 16:03

Jon Skeet