[英]What is the best way to create a copy of a Map using pass-by-value?
If I have a Java map with 100s of values in it, and I wanted to create another copy of it using this code : 如果我有一个包含100个值的Java映射,并且我想使用以下代码创建它的另一个副本:
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. 然后,如果我在map1的任何Vector条目中更改任何值,它也会在map2中受到影响。 I do not want that.
我不要那个。 I want map2 to be totally independent on map1.
我希望map2在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. 当然,你不必深入到这一点 - 因为
String
是不可变的。
(Any reason you're using Vector
rather than ArrayList
, by the way?) (顺便说一句,你使用
Vector
而不是ArrayList
原因是什么?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.