We have learnt how to iterate a collection using iterator, now lets see how to remove a element from a collection while iterating itself. The remove() method of the iterator will let us remove the element from the underlying collection.
package com.javainterviewpoint; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JavaIteratorExample_Remove { public static void main(String args[]) { //Create a List (tempList) List tempList = new ArrayList(); //Populating our list tempList.add("Java"); tempList.add("Interview"); tempList.add("Point"); tempList.add("JavaIterator"); tempList.add("Example"); System.out.println("TempList before removing element"); System.out.println(tempList); Iterator it1 = tempList.iterator(); while(it1.hasNext()) { if("Point".equals(it1.next())) { //remove() method will let us remove the element without any exception it1.remove(); } } System.out.println("TempList after removing element"); System.out.println(tempList); } }
Output
TempList before removing element [Java, Interview, Point, JavaIterator, Example] TempList after removing element [Java, Interview, JavaIterator, Example]
List itself has the remove() method when you try to modify a list while iterating it will throw you ConcurrentModificationException and hence it is safe to use the remove() method of the iterator
package com.javainterviewpoint; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JavaIteratorExample_Remove { public static void main(String args[]) { //Create a List (tempList) List tempList = new ArrayList(); //Populating our list tempList.add("Java"); tempList.add("Interview"); tempList.add("Point"); tempList.add("JavaIterator"); tempList.add("Example"); //Get the iterator object using iterator() method of the collection Iterator it = tempList.iterator(); //hasNext() will return true if the collection has more elements while(it.hasNext()) { if("Point".equals(it.next())) tempList.remove(3); } } }
Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(Unknown Source) at java.util.AbstractList$Itr.next(Unknown Source) at com.javainterviewpoint.JavaIteratorExample_Remove.main(JavaIteratorExample_Remove.java:26)
Leave a Reply