Two Java list objects having the same link?

I use two Java list objects that contain some data.

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

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

Here is the code below, which copies the entire contents of the original list into a new list and then changes the copied list to delete some items.

The problem I am facing is that it seems to fire and remove the 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();
            }
        }
+4
source share
2 answers

In this line of code:

deviceList = App.devices;

, .

, , : ArrayList , Collection .

, :

private List<Device> deviceList = new ArrayList(App.devices);
+3

deviceList = App.devices; , App.devices. ArrayList deviceList = new ArrayList(App.devices). ArrayList .

, Device , . , deviceList, Device. , Deep Shallow copy.

+2

Source: https://habr.com/ru/post/1568352/


All Articles