I have seen in many places that it says when removing an element from an ArrayList while iterating, I should be using iterator remove method instead of collections remove method to avoid concurrent modification exception.
However, below code works fine using Java 1.8 Collection remove without giving concurrent modification exception. You can see that I am not using iterator here to remove the object.
List<MyObject> list = new ArrayList<MyObject>();
list.add(new MyObject());
list.add(new MyObject());
list.add(new MyObject());
for (int i=0; i<list.size(); i++) {
list.remove(i);
}
Your example will not throw an exception. It also won't remove all elements from the list, though.
list.size()
is 1 which is less than 2At first, I thought it would throw an IndexOutOfBoundsException
, but the fact that list.size()
is evaluated at the start of each iteration ensures that it won't.
ConcurrentModificationException
Because you're not using an iterator.
This exception is thrown if you iterate the list using an iterator, then modify (e.g. delete from) the list, and then try to advance the iterator, like this:
Iterator<MyObject> it = list.iterator();
while (it.hasNext()) {
list.remove(it.next());
}
As @Ferrybig noted, even in such case the iterator might not actually throw an exception - see related question.