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

If I have a Java map with 100 values ​​in it, and I would like 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 element for map1, it will also be affected in map2. I do not need this. I want map2 to be completely independent of map1.

What is the best way to do this?

+4
source share
1 answer

Basically, you 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 do not need to go deeper, though, of course, because String immutable.

(Any reason you use Vector , not ArrayList , by the way?)

+9
source

Source: https://habr.com/ru/post/1433510/


All Articles