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

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

问题描述

我正在尝试将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天全站免登陆