views:

1137

answers:

4

what is the exact different of both.. is using enumeration more benefit than using iterator..? can anyone elaborate.. any reference article would be appeciated

+2  A: 

I used a google search and the first result was an interesting discussion in JavaRanch about Enumeration vs Iterator

victor hugo
+1 for using lmgtfy :)
Andreas_D
Hehe I could not resist
victor hugo
+10  A: 

Looking at the Java API Specification for the Iterator interface, there is an explanation of the differences between Enumeration:

Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

The bottom line is, both Enumeration and Iterator will give successive elements, but Iterator is improved in such a way so the method names are shorter, and has an additional remove method. Here is a side-by-side comparison:

  Enumeration                     Iterator
  ----------------                ----------------
  hasMoreElement()                hasNext()
  nextElement()                   next()
  N/A                             remove()

As also mentioned in the Java API Specifications, for newer programs, Iterator should be preferred over Enumeration, as "Iterator takes the place of Enumeration in the Java collections framework." (From the Iterator specifications.)

coobird
+1  A: 

"Officially", they are supposed to be similar with the iterator interface supporting extra operations (e.g., removal). Generally, the tendency is to use iterators.

Here is from the enumeration interface javadocs:

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.

Uri
A: 

If you're writing your own collection class, and you're extending any of the existing classes or implementing any of the Collections framework interfaces, you basically have no choice but to use Iterator.

If for some reason (that I can't think of) you're creating a custom collection class that does not relate to java.util.Collection or java.util.Map in any way, you should still implement Iterable so people can use your class in for loops.

Licky Lindsay