remove trap in java collection iterator Iterator

  • 2020-05-09 18:43:03
  • OfStack

package TestList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

public class TestIterator {

      /**
      * @param args
      */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
              List < String > list = new ArrayList < String > ();
              list.add("aaa");
              list.add("bbb");
              list.add("ccc");
              Iterator t = list.iterator();
              while(t.hasNext()){
    // when traversing the list collection with iterator, if you want to delete any element in the list collection, you must do so while traversing the penultimate element
                          list.remove("ccc");
                    }
              }
             
              TreeSet < String > set = new TreeSet < String > ();
              set.add("ddd");
              set.add("eee");
              set.add("fff");
              Iterator t1 = set.iterator();
              while(t1.hasNext()){
              if(t1.next ().equals("fff")){  // if you want to delete any element in the set collection while traversing the set collection with iterator, You have to delete it exactly when you're going through the penultimate element
                          set.remove("eee");
                    }
              }
      }

}

Since List and Set have 1 definite difference in the implementation of Iterator, List and Set will have different performances when deleting collection elements at the same time of iteration


Related articles: