Java 中 Map 的浅拷贝
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2356809/
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
Shallow copy of a Map in Java
提问by dcp
As I understand it, there are a couple of ways (maybe others as well) to create a shallow copy of a Map
in Java:
据我了解,有几种方法(也许还有其他方法)可以Map
在 Java 中创建 a 的浅拷贝:
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> shallowCopy;
// first way
shallowCopy = new HashMap<String, Object>(data);
// second way
shallowCopy = (Map<String, Object>) ((HashMap<String, Object>) data).clone();
Is one way preferred over the other, and if so, why?
一种方式是否优于另一种方式,如果是,为什么?
One thing worth mentioning is that the second way gives an "Unchecked Cast" warning. So you have to add @SuppressWarnings("unchecked")
to get around it, which is a little irritating (see below).
值得一提的是,第二种方式给出了“未经检查的强制转换”警告。所以你必须添加@SuppressWarnings("unchecked")
来绕过它,这有点刺激(见下文)。
@SuppressWarnings("unchecked")
public Map<String, Object> getDataAsMap() {
// return a shallow copy of the data map
return (Map<String, Object>) ((HashMap<String, Object>) data).clone();
}
采纳答案by polygenelubricants
It's always better to copy using a copy constructor. clone()
in Java is broken (see SO: How to properly override clone method?).
使用复制构造函数进行复制总是更好。clone()
Java 中的内容已损坏(请参阅 SO:如何正确覆盖克隆方法?)。
Josh Bloch on Design - Copy Constructor versus Cloning
If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think
clone
is deeply broken. [...] It's a shame thatCloneable
is broken, but it happens.
如果你读过我书中关于克隆的文章,特别是如果你在字里行间读过,你就会知道我认为它
clone
被深深地打破了。[...] 很遗憾Cloneable
被打破了,但它发生了。
Bloch (who by the way, designed and implemented the Collection framework) even went further in saying that he only provides the clone()
method just "because people expect it". He does NOT actually recommend using it at all.
Bloch(顺便说一下,他设计并实现了 Collection 框架)甚至更进一步说,他提供的clone()
方法只是“因为人们期望它”。他实际上根本不建议使用它。
I think the more interesting debate is whether a copy constructor is better than a copy factory, but that's a different discussion altogether.
我认为更有趣的争论是复制构造函数是否比复制工厂更好,但那是完全不同的讨论。
回答by Luca Fagioli
Neither of the two: the constructorthat you are referring to is defined for the HashMapimplementation of a Map, (as well as for others) but not for the Map interface itself (for example, consider the Providerimplementation of the Map interface: you will not find that constructor).
两者都不是:您所指的构造函数是为Map的HashMap实现(以及其他)定义的,而不是为 Map 接口本身定义的(例如,考虑Map 接口的Provider实现:您不会找到那个构造函数)。
On the other hand it is not advisable to use the clone()
method, as explained by Josh Bloch.
另一方面clone()
,正如 Josh Bloch 所解释的那样,不建议使用该方法。
In respect of the Map interface (and of your question, in which you ask how to copy a Map, not a HashMap), you should use Map#putAll():
关于 Map 接口(以及您询问如何复制 Map 而不是 HashMap 的问题),您应该使用Map#putAll():
Copies all of the mappings from the specified map to this map (optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map.
将所有映射从指定映射复制到此映射(可选操作)。此调用的效果等同于对指定映射中从键 k 到值 v 的每个映射在此映射上调用一次 put(k, v) 的效果。
Example:
例子:
// HashMap here, but it works for every implementation of the Map interface
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> shallowCopy = new HashMap<String, Object>();
shallowCopy.putAll(data);
回答by Terris
Copy a map without knowing its implementation:
在不知道其实现的情况下复制地图:
static final Map shallowCopy(final Map source) throws Exception {
final Map newMap = source.getClass().newInstance();
newMap.putAll(source);
return newMap;
}