如何制作ArrayList的分离副本? [英] How to make a separated copy of an 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
?
谢谢
推荐答案
是的,这是正确的 - 你需要实现 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
并使用对相同对象的引用填充它,这就是为什么从 List
中可以看到对象的更改的原因。使用克隆方法,您的代码将如下所示:
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 List
s. 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());
}
编辑:为了澄清,上面的代码是执行原始列表
的深层复制,其中新的列表
包含对副本的引用原始物体。这与调用 ArrayList.clone()
形成对比,后者执行列表的
。在此上下文中,浅拷贝创建一个新的浅拷贝
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屋!