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








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





import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class ArrayListTest {
   public static void main(String args[]) {
      // creates array with initial capacity of 10.
      List<String> arrayList = new ArrayList<String>();
      arrayList.add("ankit");
      arrayList.add("javaMadeSoEasy");
      System.out.println("-------use iterator-------");
      Iterator<String> iterator = arrayList.iterator();
      while (iterator.hasNext()) {
             System.out.println(iterator.next());
      }
      System.out.println("-------use listIterator-------");
      ListIterator<String> listIterator = arrayList.listIterator();
      listIterator.next();
      listIterator.previous();
      while (listIterator.hasNext()) {
             System.out.println(listIterator.next());
      }
      System.out.println("-------use Enumeration-------");
      Enumeration<String> listEnum = Collections.enumeration(arrayList);
      while (listEnum.hasMoreElements()) {
             System.out.println(listEnum.nextElement());
      }
      System.out.println("-------use enhanced for loop-------");
      for (String string : arrayList) {
             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>

ArrayList - add, add element at specific index methods program


ArrayList - remove, get, contains and set methods program


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


ArrayList - isEmpty, size and clear methods program


ArrayList - synchronizing using Collections.synchronizedList


ArrayList - making list unmodifiable using Collections.unmodifiableList


Vector - add, add element at specific index methods program


eEdit
Must read for you :