Java - 复制 arraylist 对象 [英] Java - copying arraylist objects

查看:41
本文介绍了Java - 复制 arraylist 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个数组列表的内容复制到另一个对象中.我尝试通过以下方式初始化新的 ArrayList 对象

I am trying to copy the contents of an arraylist into another object. I tried initializing the new ArrayList object in the following ways

newArrList.addAll(oldArrList);

newArrList = new ArrayList(oldArrList);

但是每次我对其中一个数组列表进行更改时,另一个 ArrayList 中的值也会发生变化.

But every time I make a change to one of the array lists, the value also changes in the other ArrayList.

谁能告诉我如何避免这种情况.

Can someone please tell me how I can avoid this.

谢谢.

推荐答案

ArrayList 将只包含对对象的引用 - 而不是对象本身.当您将一个列表的内容复制到另一个列表时,您就是在复制这些引用.这意味着这两个列表将引用相同的对象.

The ArrayList will only contain references to objects - not the objects themselves. 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.

这篇关于Java - 复制 arraylist 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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