LinkedHashSet - fail-fast iteration using iterator, Enumeration and enhanced for loop example program in java


LinkedHashSet - fail-safe or fail-fast iteration using iterator, Enumeration and enhanced for loop program.

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


import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class LinkedHashSetIteratorFailFastExample {
   public static void main(String args[]) {
      Set<String> linkedLinkedHashSet = new LinkedHashSet<String>();
      linkedLinkedHashSet.add("ankit");
      linkedLinkedHashSet.add("javaMadeSoEasy");
      System.out.println("-------use iterator-------");
      // fail-fast
      Iterator<String> iterator = linkedLinkedHashSet.iterator();
      while (iterator.hasNext()) {
             linkedLinkedHashSet.add("newElement1");//unComment to avoid ConcurrentModificationException
             System.out.println(iterator.next());
      }
      System.out.println("-------use Enumeration-------");
      // fail-fast
      Enumeration<String> listEnum = Collections.enumeration(linkedLinkedHashSet);
      while (listEnum.hasMoreElements()) {
             linkedLinkedHashSet.add("newElement2");//unComment to avoid ConcurrentModificationException
             System.out.println(listEnum.nextElement());
      }
      System.out.println("-------use enhanced for loop-------");
      // enhanced for loop is fail-fast
      for (String string : linkedLinkedHashSet) {
             linkedLinkedHashSet.add("newElement3");//unComment to avoid ConcurrentModificationException
             System.out.println(string);
      }
   }
}
/*OUTPUT
-------use iterator-------
Exception in thread "main" java.util.ConcurrentModificationException
   at java.util.LinkedHashMap$LinkedHashIterator.nextNode(Unknown Source)
   at java.util.LinkedHashMap$LinkedKeyIterator.next(Unknown Source)
   at LinkedHashSetIteratorFailFastExample.main(LinkedHashSetIteratorFailFastExample.java:25)
*/



RELATED LINKS>


HashSet - iterate using iterator, Enumeration and enhanced for loop program


HashSet - making set unmodifiable using Collections.unmodifiableSet


CopyOnWriteArraySet - add, contains, remove, size methods program


eEdit
Must read for you :