Java 中 Map 的浅拷贝

发布于 2024-08-23 04:18:56 字数 744 浏览 3 评论 0原文

据我了解,有几种方法(也许还有其他方法)可以在 Java 中创建 Map 的浅表副本:

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();

是否一种方法优于另一种方法,如果是,为什么?

值得一提的是,第二种方式给出了“Unchecked Cast”警告。所以你必须添加 @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();
}

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<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")
public Map<String, Object> getDataAsMap() {
    // return a shallow copy of the data map
    return (Map<String, Object>) ((HashMap<String, Object>) data).clone();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七婞 2024-08-30 04:18:56

使用复制构造函数进行复制总是更好。 Java 中的 clone() 已损坏(参见 SO:如何正确重写克隆方法?)。

Josh Bloch 谈设计 - 复制构造函数与克隆

如果你读过我书中有关克隆的内容,特别是如果你读到了字里行间的内容,你就会知道我认为克隆已经被彻底破坏了。 [...] 遗憾的是 Cloneable 被破坏了,但它确实发生了。

Bloch(顺便说一句,他设计并实现了 Collection 框架)甚至进一步表示,他只提供 clone() 方法只是“因为人们期望它”。他实际上根本不建议使用它。


我认为更有趣的争论是复制构造函数是否比复制工厂更好,但这完全是一个不同的讨论。

It's always better to copy using a copy constructor. clone() in Java is broken (see SO: How to properly override clone method?).

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 that Cloneable is broken, but it happens.

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.


I think the more interesting debate is whether a copy constructor is better than a copy factory, but that's a different discussion altogether.

静待花开 2024-08-30 04:18:56

两者都不是:构造函数<您所指的 /a> 是为 HashMap 实现定义的Map 的,(以及其他),但不适用于Map 接口本身(例如,考虑 Provider 的实现Map接口:你不会找到那个构造函数)。

另一方面,正如 Josh Bloch 所解释的,不建议使用 clone() 方法。

关于 Map 接口(以及您的问题,您询问如何复制 Map,而不是 HashMap),您应该使用 Map#putAll():

将指定映射的所有映射复制到此映射
(可选操作)。这个调用的效果相当于
对于从键 k 到键的每个映射,在此映射上调用一次 put(k, v) 一次
指定映射中的值 v。

例子:

// 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);

Neither of the two: the constructor that you are referring to is defined for the HashMap implementation of a Map, (as well as for others) but not for the Map interface itself (for example, consider the Provider implementation of the Map interface: you will not find that constructor).

On the other hand it is not advisable to use the clone() method, as explained by 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():

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.

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);
木有鱼丸 2024-08-30 04:18:56

在不知道其实现的情况下复制映射:

static final Map shallowCopy(final Map source) throws Exception {
    final Map newMap = source.getClass().newInstance();
    newMap.putAll(source);
    return newMap;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文