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








CopyOnWriteArrayList - iterate using iterator, listIterator, Enumeration and enhanced for loop.


import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListTest {
   public static void main(String args[]) {
      List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<String>();
      copyOnWriteArrayList.add("ankit");
      copyOnWriteArrayList.add("javaMadeSoEasy");
      System.out.println("-------use iterator-------");
      Iterator<String> iterator = copyOnWriteArrayList.iterator();
      while (iterator.hasNext()) {
             System.out.println(iterator.next());
      }
      System.out.println("-------use listIterator-------");
      ListIterator<String> listIterator = copyOnWriteArrayList.listIterator();
      while (listIterator.hasNext()) {
             System.out.println(listIterator.next());
      }
      System.out.println("-------use Enumeration-------");
      Enumeration<String> listEnum = Collections
                   .enumeration(copyOnWriteArrayList);
      while (listEnum.hasMoreElements()) {
             System.out.println(listEnum.nextElement());
      }
      System.out.println("-------use enhanced for loop-------");
      for (String string : copyOnWriteArrayList) {
             System.out.println(string);
      }
   }
}
/*OUTPUT
-------use iterator-------
ankit
javaMadeSoEasy
-------use listIterator-------
ankit
javaMadeSoEasy
-------use Enumeration-------
ankit
javaMadeSoEasy
-------use enhanced for loop-------
ankit
javaMadeSoEasy
*/




RELATED LINKS>


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


CopyOnWriteArrayList - isEmpty, size and clear methods program



eEdit
Must read for you :