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 ?
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With