/* * This example shows the wrong and right way to remove items from a * LinkedList or similar structure. * * The problem is one of using an Iterator over a structure while items * are being removed from the structure itself. */ package linkedlistillustration; import java.util.LinkedList; /** * * @author Robert Keller */ public class Main { public static void main(String[] args) { LinkedList L = new LinkedList(); L.add(2); L.add(3); L.add(4); L.add(5); // Wrong way to remove even items from the list L: // // for( Object i: L) // This is an implied iterator. // { // if( ((Integer)i).intValue() % 2 == 0 ) // { // L.remove(i); // } // } // // The above will not work. It will produce the following runtime exception: // Exception in thread "main" java.util.ConcurrentModificationException // at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:761) // at java.util.LinkedList$ListItr.next(LinkedList.java:696) // at linkedlistillustration.Main.main(Main.java:31) // This is the correct way to remove selected items. // First make a separate list of the items to be removed. LinkedList Removal = new LinkedList(); for( Object i: L) { if( ((Integer)i).intValue() % 2 == 0 ) { Removal.add(i); } } // Then iterate over the list of items to be removed and remove // each individually from the original list. // Here we are NOT ITERATING over the original list, so // concurrent removal is not a problem. for( Object i: Removal) { L.remove(i); } System.out.println(L); } }