java list 相同对象吗,具有相同的参考两个Java List对象?

I am using two java List objects that contain some data.

the first list contains all the data objects inside it and teh second one contains some of the data(not all) from the original list.

The original list itself is a static object that can be accessed .

Here is the code below that copies the whole contents of the original list into a new List and then ammends the copied list my removing certain elements.

The issue i am having is that it seems to effect and remove same elements from the Original list!

private List deviceList;

deviceList = App.devices;

//check which devices have not been added by checking the position data

for (Iterator iterator = deviceList.iterator(); iterator.hasNext(); ) {

Device device = iterator.next();

if (device.getPosition() != Device.NO_POSITION) {

iterator.remove();

}

}

解决方案

In this line of code:

deviceList = App.devices;

you are not copying the list, but creating another reference to it.

To make a shallow copy of the list you can use for example: ArrayList constructor which accepts Collection as a parameter and makes copy.

So it should be like that:

private List deviceList = new ArrayList(App.devices);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值