如何制作 ArrayList 的单独副本? [英] How to make a separated copy of an ArrayList?

查看:31
本文介绍了如何制作 ArrayList 的单独副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java:如何克隆 ArrayList 并克隆其项目?

我有一个如下所示的示例程序:

I have a sample program like the following:

ArrayList<Invoice> orginalInvoice = new ArrayList<Invoice>();

//add some items into it here

ArrayList<Invoice> copiedInvoice = new ArrayList<Invoice>();

copiedInvoice.addAll(orginalInvoice);


我以为我可以修改 copiedInvoice 内的项目,它不会影响 originalInoice 内的这些项目.但是我错了.


I thought I can modify items inside the copiedInvoice and it will not affect these items inside originalInoice. But I was wrong.

如何制作 ArrayList 的单独副本/克隆?

How can I make a separated copy / clone of an ArrayList?

谢谢

推荐答案

是的,这是正确的 - 您需要实现 clone()(或其他合适的机制来复制您的对象,如 clone() 被很多程序员认为是破的").您的 clone() 方法应该执行对象中所有可变字段的深层复制.这样,对克隆对象的修改不会影响原始对象.

Yes that's correct - You need to implement clone() (or another suitable mechanism for copying your object, as clone() is considered "broken" by many programmers). Your clone() method should perform a deep copy of all mutable fields within your object. That way, modifications to the cloned object will not affect the original.

在您的示例代码中,您正在创建第二个 ArrayList 并用对相同对象的引用填充它,这就是为什么对对象的更改从两个<代码>列表.使用克隆方法,您的代码将如下所示:

In your example code you're creating a second ArrayList and populating it with references to the same objects, which is why changes to the object are visible from both Lists. With the clone approach your code would look like:

List<Foo> originalList = ...;

// Create new List with same capacity as original (for efficiency).
List<Foo> copy = new ArrayList<Foo>(originalList.size());

for (Foo foo: originalList) {
  copy.add((Foo)foo.clone());
}

EDIT:澄清一下,上面的代码正在执行原始List深度复制,从而新的List 包含对原始对象副本的引用.这与调用 ArrayList.clone() 形成对比,后者执行 List浅拷贝.在这种情况下,浅拷贝创建了一个新的 List 实例,但包含对原始对象的引用.

EDIT: To clarify, the above code is performing a deep copy of the original List whereby the new List contains references to copies of the original objects. This contrasts to calling ArrayList.clone(), which performs a shallow copy of the List. In this context a shallow copy creates a new List instance but containing references to the original objects.

这篇关于如何制作 ArrayList 的单独副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆