-->

Removing an object from the duplicate ArrayList on

2019-09-16 16:42发布

问题:

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.

回答1:

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);