2

I'm a newbie in java, I want to traverse the elements in a Vector. I'm getting the same result when I use Iterator / Enumeration interfaces.

As Vector is slow because it is synchronized. Does it enhance the performance in any aspect if I use Iterator / Enumeration.

Here's what I've tried

import java.util.*;

class vectorClass{
public static void main(String args[]){

    Vector<String> vector = new Vector<String>();
    vector.add("This is a vector Example\n");
    vector.add("This is a next line!");

    Enumeration en = vector.elements();
    while(en.hasMoreElements()){
        System.out.print(en.nextElement());
    }

    System.out.println();
    Iterator en1 = vector.iterator();
    while(en1.hasNext()){
        System.out.print(en1.next());
    }
}
}

O/P:

This is a vector Example

This is a next line!

This is a vector Example

This is a next line!

Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50

1 Answers1

3

There are no performance differences between Enumeration or Iterator. However, I would foster the use of Iterator since Enumeration is now deprecated (from the doc):

NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

By the way, if you are not forced to use Vector, use ArrayList instead since Vector is slower because of constant synchronization but still not thread-safe. See this answer for details.

From the javadoc, it is also recommended to use ArrayList instead of Vector:

Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

Community
  • 1
  • 1
Spotted
  • 4,021
  • 17
  • 33