Can you remove an element from a collection while iterating over it? Answer: No, you can’t.
What kind of error will you get in Java if you make an attempt? Compile time or Runtime? Answer: Runtime.
The details of the exception will be as below. Check this along with a sample program that I wrote. You can try to compile and run it yourself to see the result.
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)
package com.salesforce.test;
import java.util.List;
import java.util.ArrayList;
/**
* To compiple: javac -d . RemoveListTest.java
* To run: java com.salesforce.test.RemoveListTest
*
* @author ashik
*/
public class RemoveListTest {
public List counts = new ArrayList();
public RemoveListTest() {
counts.add(0);
counts.add(1);
counts.add(2);
counts.add(3);
counts.add(4);
counts.add(5);
counts.add(6);
counts.add(7);
counts.add(8);
counts.add(9);
counts.add(10);
counts.add(11);
counts.add(12);
counts.add(13);
counts.add(14);
}
public static void main(String[] args) {
System.out.println("\nRemoveListTest starts.....\n");
RemoveListTest rlt = new RemoveListTest();
List results = new ArrayList();
for(Integer count : rlt.counts) {
System.out.println("count before removing = " + count);
if(count % 3 == 1) {
results.add(count);
// rlt.counts.remove(count); // you will get runtime error if you uncomment it
}
}
for(Integer result : results) {
System.out.println("result = " + result);
rlt.counts.remove(result);
}
for(Integer count : rlt.counts) {
System.out.println("count after removing = " + count);
}
System.out.println("\nRemoveListTest ends.....\n");
}
}