java中HashMap的克隆实用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/998376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
clone utility for HashMap in java
提问by Moro
Is there java utility that does clone()
method for HashMap
such that it does copy of the map elements not just the map object (as the clone()
in HashMap
class)?
是否有 java 实用程序可以执行clone()
方法以便HashMap
它复制地图元素而不仅仅是地图对象(如clone()
inHashMap
类)?
采纳答案by Michael Borgwardt
What about other objects referred to in the elements? How deep do you want your clone?
元素中引用的其他对象呢?你想要你的克隆有多深?
If your map elements don't have any deep references and/or everything is Serializable
, you can serialize the map via ObjectOutputStream
into a ByteArrayOutputStream
and then deserialize it right away.
如果您的地图元素没有任何深度引用和/或一切都是Serializable
,您可以将地图 via 序列ObjectOutputStream
化为 aByteArrayOutputStream
然后立即反序列化。
The only other alternative is to do it manually.
唯一的其他选择是手动完成。
回答by Oso
Once you know your key/value pair elements are cloneable:
一旦你知道你的键/值对元素是可克隆的:
HashMap<Foo, Bar> map1 = populateHashmap();
HashMap<Foo, Bar> map2 = new HashMap<Foo, Bar>();
Set<Entry<Foo, Bar>> set1 = map1.entrySet();
for (Entry<Foo, Bar> e : l)
map2.put(e.getKey().clone(), e.getValue().clone());
回答by Matthew Flaschen
Take a look at the deepClone method at http://www.devdaily.com/java/jwarehouse/netbeans-src/db/libsrc/org/netbeans/lib/ddl/impl/SpecificationFactory.java.shtml. It is not generic, but it includes several built-in types (including HashMap itself, recursively), and can obviously be extended.
在http://www.devdaily.com/java/jwarehouse/netbeans-src/db/libsrc/org/netbeans/lib/ddl/impl/SpecificationFactory.java.shtml查看 deepClone 方法。它不是通用的,但它包含几个内置类型(包括 HashMap 本身,递归),并且显然可以扩展。
回答by Ian Durkan
The SO question Deep clone utility recommendationis similar to this one, and has an answer that may be helpful to you.
SO问题Deep clone实用程序推荐与此类似,并且有一个可能对您有所帮助的答案。
To summarize, they recommend using the Cloning libraryfrom Google Code. From personal experience, it deep-copies HashMap
s. It can even clone things that aren't Cloneable
.
总而言之,他们建议使用Google Code的 Cloning 库。从个人经验来看,它深拷贝HashMap
s。它甚至可以克隆不是Cloneable
.
回答by Andrey
Often copy should be deep. Here is an example how to "deep copy"
常文案应深。这是一个如何“深拷贝”的例子
Map<Integer, ArrayList<Integer>>
code:
代码:
public static Map<Integer, ArrayList<Integer>> deepCopyMapIntList
(Map<Integer, ArrayList<Integer>> original) {
Map<Integer, ArrayList<Integer>> copy = new HashMap<>(original.size());
for (int i : original.keySet()) {
ArrayList<Integer> list = original.get(i);
copy.put(i, (ArrayList<Integer>) list.clone());
}
return copy;
}