Search code examples
javaiteratorconcurrentmodification

Removing an object from the duplicate ArrayList only


I've copied an ArrayList over as so:

MyList2 = MyList1;

In an attempt to load MyList2's objects with the ones which MyList1 has.

Now as I iterate through MyList2, I it.remove() some objects, but this is causing a concurrent modification exception elsewhere on the parent iteration through MyList1. I think when i it.remove() it's actually removing it from the original ArrayList as well, how do remove it only from MyList2? Thanks.


Solution

  • Your problem there is that you haven´t created a copy of the ArrayList, there are two references to the same object. If you want to copy the list, then you could do

    Collections.copy(MyList2,MyList1);
    

    or

    MyList2 = new ArrayList(MyList1);