Skip to Content

Traverse through ArrayList in forward direction using Java ListIterator Example

  1. /*
  2.   Traverse through ArrayList in forward direction using Java ListIterator Example
  3.   This Java Example shows how to iterate through an ArrayList object
  4.   in forward direction using Java ListIterator's next and hasNext methods .
  5. */
  6.  
  7. import java.util.ListIterator;
  8. import java.util.ArrayList;
  9.  
  10. public class TraverseForwardUsingListIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.     //create an object of ArrayList
  14.     ArrayList aList = new ArrayList();
  15.    
  16.     //Add elements to ArrayList object
  17.     aList.add("1");
  18.     aList.add("2");
  19.     aList.add("3");
  20.     aList.add("4");
  21.     aList.add("5");
  22.    
  23.     //Get an object of ListIterator using listIterator() method
  24.     ListIterator listIterator = aList.listIterator();
  25.    
  26.     /*
  27.        Traverse the ArrayList in forward direction using hasNext and next methods
  28.        of ListIterator. hasNext method returns true if ListIterator has more
  29.        elements to traverse in forward direction. Next method returns next element
  30.        in the list.
  31.     */
  32.     System.out.println("Traversing ArrayList in forward direction
  33.                                                       using ListIterator");
  34.     while(listIterator.hasNext())
  35.       System.out.println(listIterator.next());
  36.   }
  37. }
  38.  
  39. /*
  40. Traversing ArrayList in forward direction using ListIterator
  41. 1
  42. 2
  43. 3
  44. 4
  45. 5
  46. */