具有相同的参考两个Java List对象? [英] Two java List objects having same reference?
问题描述
我使用的包含一些数据的两个Java列表对象。
第一个列表包含它里面的所有数据对象和德第二个包含原始列表中的某些数据(不是全部)。
的原始列表本身是可访问的静态对象。
下面是低于拷贝原始列表的全部内容到一个新的列表,然后ammends复制列表删除我的某些元素的code。
我遇到的问题是,它似乎从原来的名单影响,并删除相同的元素!
私人列表<装置> DEVICELIST;
DEVICELIST = App.devices; //检查哪些设备尚未通过检查位置数据添加 为(迭代&所述;装置>迭代= deviceList.iterator(); iterator.hasNext()){
设备device = iterator.next();
如果(device.getPosition()!= Device.NO_POSITION){
iterator.remove();
}
}
在这一行code的:
DEVICELIST = App.devices;
你是不是复制列表中,但创造它的另一个参考。
为了让你可以使用例如列表的浅表复制:的ArrayList
的构造函数,它接受收藏
作为参数,使得副本。
因此,它应该是这样的:
私人列表<装置> DEVICELIST =新的ArrayList(App.devices);
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<Device> deviceList;
deviceList = App.devices;
//check which devices have not been added by checking the position data
for (Iterator<Device> 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<Device> deviceList = new ArrayList(App.devices);
这篇关于具有相同的参考两个Java List对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!