简体   繁体   English

Java - 复制arraylist对象

[英]Java - copying arraylist objects

I am trying to copy the contents of an arraylist into another object. 我试图将arraylist的内容复制到另一个对象。 I tried initializing the new ArrayList object in the following ways 我尝试通过以下方式初始化新的ArrayList对象

newArrList.addAll(oldArrList);

and

newArrList = new ArrayList(oldArrList);

But every time I make a change to one of the array lists, the value also changes in the other ArrayList. 但每次我对其中一个数组列表进行更改时,该值也会在另一个ArrayList中更改。

Can someone please tell me how I can avoid this. 有人可以告诉我如何避免这种情况。

Thanks. 谢谢。

The ArrayList will only contain references to objects - not the objects themselves. ArrayList只包含对象的引用 - 而不是对象本身。 When you copy the contents of one list into another, you're copying those references. 将一个列表的内容复制到另一个列表时,您将复制这些引用。 That means the two lists will refer to the same objects. 这意味着两个列表将引用相同的对象。

I suspect that when you say you make a change to one of the lists, you actually mean you're making a changed to one of the objects referenced by the list. 我怀疑当你说你对其中一个列表进行更改时,你实际上意味着你正在改变列表引用的一个对象。 That's to be expected. 这是可以预料的。

If you want the lists to have references to independent objects, you'll need to make a deep copy of the objects as you copy them from one list to another. 如果希望列表具有对独立对象的引用,则在将对象从一个列表复制到另一个列表时,需要对这些对象进行深层复制 Exactly how that works will depend on the objects you're copying. 具体如何工作将取决于您正在复制的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM