我正在使用两个包含一些数据的java 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();
}
}
答案 0 :(得分:3)
在这行代码中:
deviceList = App.devices;
您没有复制列表,而是创建另一个引用。
要制作列表的浅表副本,您可以使用例如:ArrayList
构造函数,它接受Collection
作为参数并进行复制。
所以它应该是这样的:
private List<Device> deviceList = new ArrayList(App.devices);
答案 1 :(得分:2)
deviceList = App.devices;
不会创建新对象,但只会指向App.devices
对象。您可以使用ArrayList deviceList = new ArrayList(App.devices)
。这个将实例化一个新的对象ArrayList,它不会影响你的静态列表对象。
但是,请注意,对象Device
上的任何更改都将同时应用于您的列表,因为这两个列表中的两个对象都指向同一个地址。因此,如果您要对deviceList
内的对象应用单独更改,则还应创建新的Device
对象。您可能需要查看Deep and Shallow copy。