Iterate a Collection and remove an itemTag(s): Language


You get an exception if while scanning a Collection, you decide to remove an item.
import java.util.ArrayList;

public class Simple {
  public static void main(String args[]) {
    ArrayList<String> list = new ArrayList<String>();

    list.add("Bart");
    list.add("Lisa");
    list.add("Marge");
    list.add("Barney");
    list.add("Homer");
    list.add("Maggie");

    for(String s: list)
    {
      if (s.equals("Barney")) {
        list.remove("Barney");
      }
      System.out.println(s);
    }
  }

  /*
    output :
        Bart
        Lisa
        Marge
        Barney
        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.rgagnon.howto.Simple.main(Simple.java:20)   
   */
}
The trick is to use an Iterator and remove the item with Iterator.remove()
import java.util.ArrayList;
import java.util.Iterator;

public class Simple {
  public static void main(String args[]) {
    ArrayList<String> list = new ArrayList<String>();

    list.add("Bart");
    list.add("Lisa");
    list.add("Marge");
    list.add("Barney");
    list.add("Homer");
    list.add("Maggie");

    for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
      String s = iter.next();
      if (s.equals("Barney")) {
        iter.remove();
      }
      else {
        System.out.println(s);
      }
    }

    for(String s: list)
    {
      System.out.println(s);
    }
  }

  /*
    output :
        Bart
        Lisa
        Marge
        Homer
        Maggie
        Bart
        Lisa
        Marge
        Homer
        Maggie 
   */
}

blog comments powered by Disqus