beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Vector Iterator example in Java

By Chaitanya Singh | Filed Under: Java Collections

In the last tutorial we learnt how to traverse a Vector in both the directions(forward & backward) using ListIterator. In this example, we are gonna see how to traverse a Vector using Iterator. The steps are as follows:
1) Create a Vector
2) Add elements to it using add(Element E) method of Vector class
3) Obtain an iterator by invoking iterator() method of Vector.
4) Traverse the Vector using hasNext() and next() method of Iterator.

Example

import java.util.Vector;
import java.util.ListIterator;
import java.util.Iterator;
public class VectorIteratorExample {
  public static void main(String[] args) {

     // Creating a Vector of Strings
     Vector<String> vector = new Vector<String>();
 
     //Adding elements to the Vector
     vector.add("Mango");
     vector.add("Orange");
     vector.add("Apple");
     vector.add("Grapes");
     vector.add("Kiwi");
 
     //Obtaining an iterator
     Iterator it = vector.iterator();

     System.out.println("Vector elements are:");
     while(it.hasNext()){
       System.out.println(it.next());
     }
  }
}

Output:

Vector elements are:
Mango
Orange
Apple
Grapes
Kiwi

Enjoyed this post? Try these related posts

  1. How to clone an ArrayList to another ArrayList
  2. Java – Replace element in a LinkedList example
  3. Java – Get first and last elements from LinkedList example
  4. How to sort ArrayList in descending order in Java
  5. Java – Convert a LinkedList to ArrayList
  6. Hashtable Iterator example – Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap