Hiteshkumar Misro Hiteshkumar Misro - 7 months ago 22
Java Question

Iterator or Enumeration, What should I use?

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();

Iterator en1 = vector.iterator();


This is a vector Example

This is a next line!

This is a vector Example

This is a next line!


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.