Vector - fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop





Vector -  fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop.

iterator returned by Vector is fail-fast. Means any structural modification made to Vector like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.



Enumeration is fail-safe, means any modification made to Vector during iteration using Enumeration don’t throw any exception.
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class VectorTest {
   public static void main(String args[]) {
      // creates array with initial capacity of 10.
      Vector<String> vector = new Vector<String>();
      vector.add("ankit");
      vector.add("javaMadeSoEasy");
      System.out.println("-------use Enumeration-------");
      // fail-safe
      Enumeration<String> listEnum = vector.elements();
      while (listEnum.hasMoreElements()) {
             String str = listEnum.nextElement();
             if (str.equals("ankit")) {
                   // adding element will not throw any Exception
                   vector.add("newEle");
             }
             System.out.println(str);
      }
     
      System.out.println("-------use iterator-------");
      // fail-fast
      Iterator<String> iterator = vector.iterator();
          while (iterator.hasNext()) {
             vector.add("newEle"); // unComment to avoid ConcurrentModificationException
             System.out.println(iterator.next());
      }
      System.out.println("-------use listIterator-------");
      // fail-fast
      ListIterator<String> listIterator = vector.listIterator();
      listIterator.next();
      listIterator.previous();
      while (listIterator.hasNext()) {
             vector.add("newEle"); // unComment to avoid ConcurrentModificationException
             System.out.println(listIterator.next());
      }
      System.out.println("-------use enhanced for loop-------");
          //enhanced for loop is fail-fast
      for (String string : vector) {
             vector.add("newEle"); // unComment to avoid ConcurrentModificationException
             System.out.println(string);
      }
   }
}


RELATED LINKS>


Vector - remove, get, contains and set methods program


Vector - iterate using iterator, listIterator, Enumeration and enhanced for loop



No comments:

Post a Comment