Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an Element from a List inside a loop [duplicate]

Tags:

java

arraylist

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);
}
like image 371
Ryan Avatar asked May 14 '14 21:05

Ryan


1 Answers

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.

like image 63
stianlp Avatar answered Nov 14 '22 23:11

stianlp