LinkedList - iterate using iterator, listIterator, Enumeration and enhanced for loop in java







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


import java.util.LinkedList;
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 LinkedListIterateExample {
   public static void main(String args[]) {
      List<String> linkedList = new LinkedList<String>();
      linkedList.add("ankit");
      linkedList.add("javaMadeSoEasy");
      System.out.println("-------use iterator-------");
      Iterator<String> iterator = linkedList.iterator();
      while (iterator.hasNext()) {
             System.out.println(iterator.next());
      }
      System.out.println("-------use listIterator-------");
      ListIterator<String> listIterator = linkedList.listIterator();
      listIterator.next();
      listIterator.previous();
      while (listIterator.hasNext()) {
             System.out.println(listIterator.next());
      }
      System.out.println("-------use Enumeration-------");
      Enumeration<String> listEnum = Collections.enumeration(linkedList);
      while (listEnum.hasMoreElements()) {
             System.out.println(listEnum.nextElement());
      }
      System.out.println("-------use enhanced for loop-------");
      for (String string : linkedList) {
             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


No comments:

Post a Comment