I wanted to remove a range of items from a list using the List.subList method. I tried the following: // al is defined previously as ArrayList al = new ArrayList();
List l = al.subList(20,50);
al.removeAll(l);
That got me the java.util.ConcurrentModificationException
The documentation says that a subList is dependent on the List that it is sublisting from. So, while a sublist is open, it is manipulating the parent list and seems to have a lock on it. Instead, you can create a brand new ArrayList and fill it with the subList, thus freeing up the sublist so that a future call can modify the original List:
ArrayList sl = new ArrayList(al.subList(10,40));
al.removeAll(sl);
So why does
List = myList.subList(10,30);
get you a different animal than
ArrayList temp = new ArrayList(myList.subList(10,30)); ??
because in the first snippet, I haven't instantiated a new object, I just created a reference to an existing object. In the second snippet, I created a brand new object. That's what the word "new" gets me.
6:06:45 PM
|