CodesJava

Easy learning with example program codes

how to read all elements in vector by using iterator?


The java.util.Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. It extends AbstractList and implements List interfaces.

We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.

Example:

package com.codesjava;
 
import java.util.Iterator;
import java.util.Vector;
 
public class Test {
  public static void main(String args[]){
	Vector<String> vector = new Vector<String>();
        //adding elements to the end
	vector.add("Jai");
	vector.add("Mahesh");
	vector.add("Hemant");
	vector.add("Vishal");
	Iterator<String> iterator = vector.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
  }
}

Output

Jai
Mahesh
Hemant
Vishal


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap