java arraylist拷贝,Java-复制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);

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.

Can someone please tell me how I can avoid this.

Thanks.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值