Skip to Content

Iterate through elements Java Vector using ListIterator Example

  1. /*
  2.   Iterate through elements Java Vector using ListIterator Example
  3.   This Java Example shows how to iterate through the elements of java
  4.   Vector object in forward and backward direction using ListIterator.
  5. */
  6.  
  7. import java.util.Vector;
  8. import java.util.ListIterator;
  9.  
  10. public class IterateThroughVectorUsingListIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create Vector object
  15.     Vector v = new Vector();
  16.    
  17.     //Add elements to Vector
  18.     v.add("1");
  19.     v.add("2");
  20.     v.add("3");
  21.     v.add("4");
  22.     v.add("5");
  23.    
  24.     /*
  25.       Get a ListIterator object for Vector using
  26.       listIterator() method.
  27.     */
  28.     ListIterator itr = v.listIterator();
  29.    
  30.     /*
  31.       Use hasNext() and next() methods of ListIterator to iterate through
  32.       the elements in forward direction.
  33.     */
  34.     System.out.println("Iterating through Vector elements in forward direction...");
  35.     while(itr.hasNext())
  36.       System.out.println(itr.next());
  37.  
  38.     /*
  39.       Use hasPrevious() and previous() methods of ListIterator to iterate through
  40.       the elements in backward direction.
  41.     */
  42.     System.out.println("Iterating through Vector elements in backward direction...");
  43.     while(itr.hasPrevious())
  44.       System.out.println(itr.previous());
  45.    
  46.   }
  47. }
  48.  
  49. /*
  50. Output would be
  51. Iterating through Vector elements in forward direction...
  52. 1
  53. 2
  54. 3
  55. 4
  56. 5
  57. Iterating through Vector elements in backward direction...
  58. 5
  59. 4
  60. 3
  61. 2
  62. 1
  63. */