How to Iterate Through Vector Elements in Java


The example aims to iterate through the elements of Vector by ListIterator in Java.

Source Code

package com.beginner.examples;

import java.util.ListIterator;
import java.util.Vector;

public class IterateThroughVectorUsingListIterator {

	public static void main(String[] args) {
		
		//create Vector.
		Vector vector = new Vector();
	    
		vector.add("A");
		vector.add("B");
		vector.add("C");
		vector.add("D");
		
		/*
		 * Get a ListIterator object for Vector using listIterator method.
		 */
		ListIterator listIterator = vector.listIterator();
		System.out.println("Iterating through Vector elements :");
		while(listIterator.hasNext()) {
			System.out.println(listIterator.next());
		}

	}

}

Output:

Iterating through Vector elements :
A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Iterate Through Vector Elements in Java


The example aims to learn how to iterate through the elements of Vector by Iterator in Java.

Source Code

package com.beginner.examples;

import java.util.Iterator;
import java.util.Vector;

public class IterateThroughVectorUsingIterator {

	public static void main(String[] args) {
		
		//create Vector.
		Vector vector = new Vector();
	    
		vector.add("A");
		vector.add("B");
		vector.add("C");
		vector.add("D");
		
		/*
		 * get an Iterator object for Vector using iterator method.
		 */
		Iterator iterator = vector.iterator();
		
		System.out.println("Iterating through Vector elements...");
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}

}

Output:

Iterating through Vector elements...
A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Iterate Through Vector Elements in Java


Here we will write an example to show how to iterate through elements of a Vector with Enumeration in Java.

Source Code

package com.beginner.examples;

import java.util.Enumeration;
import java.util.Vector;

public class TraverseVectorUseEnumerationExample {

	
	public static void main(String[] args) {
	
		//Create a Vector object
		Vector vector = new Vector();
		
		//Add elements
		vector.add("A");
		vector.add("B");
		vector.add("C");
		vector.add("D");
		
		//Get the Enumeration object with the elements() method
		Enumeration enumVector = vector.elements();
		/*
		 * Use the hasMoreElements() method to determine if there is next value
		 */
		while(enumVector.hasMoreElements())
		{
			
			String element = enumVector.nextElement();
			System.out.println(element);
		}

	}

}

Output:

A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments