Pregunta

I'm trying to delete an element from an ArrayList inside a loop.

This is OK.

ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
for(Integer i: list){
    if(i == 2)
        list.remove(i);
}

But this is not, and throw concurrentMOdificationException.

 ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
 for(Integer i: list){
        list.remove(i);
 }

I don't understand why.

I just added another element, it is not OK either (throw concurrentMOdificationException).

ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));

System.out.println(list);

for (Integer i : list) {
    if (i == 2)
        list.remove(i);
}
¿Fue útil?

Solución

Use the Iterator class instead of the for-each loop.

Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
   Integer i = it.next();
   it.remove();
}

http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

Otros consejos

You have to understand a little bit about what is going when use a for loop of this nature. It is really using a java.util.Iterator under the hood. This iterator will use the next() method to determine when iteration should stop, and the hasNext() method to retrieve the next element.

The kicker is that only next() checks for concurrent modification - hasNext() does not perform the check. In the first case, you wait until the second loop iteration to remove 2 from the list, and the next iteration finds the end of the list and exits. In the second case, you remove the 1 from the list during the first iteration, and the next iteration throws the exception when it tries to retrieve the next element.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top