Java Remove Element from ArrayList

To remove some elements from an ArrayList while iterating over the ArrayList, we need to use Iterator.

Integer[] arr = {1,2,3,4,5,6};
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
System.out.println(list);
 
Iterator<Integer> iter = list.iterator();
while(iter.hasNext()){
	int i = iter.next();
	if(i==5)
		iter.remove();
}
 
System.out.println(list);

If the element is removed by using ArrayList.remove(i) method during iteration like the following, the program will throw a ConcurrentModificationException.

for(int i: list){
	if(i==2)
		list.remove(list.indexOf(i));
}
java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
	at java.util.ArrayList$Itr.next(Unknown Source)

Java API Examples – java.util.Iterator

Leave a Comment