Loop through the Vector elements using an Iterator in Java

Java 8Object Oriented ProgrammingProgramming

An Iterator can be used to loop through the Vector elements. The method hasNext( ) returns true if there are more elements in the Vector and false otherwise. The method next( ) returns the next element in the Vector and throws the exception NoSuchElementException if there is no next element.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Iterator;
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector();
      vec.add(4);
      vec.add(1);
      vec.add(3);
      vec.add(9);
      vec.add(6);
      vec.add(8);
      System.out.println("The Vector elements are: ");
      Iterator i = vec.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

The output of the above program is as follows −

The Vector elements are:
4
1
3
9
6
8

Now let us understand the above program.

The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows −

Vector vec = new Vector();
vec.add(4);
vec.add(1);
vec.add(3);
vec.add(9);
vec.add(6);
vec.add(8);
System.out.println("The Vector elements are: ");
Iterator i = vec.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}
raja
Published on 07-Feb-2019 16:28:14
Advertisements