File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Iterator & Enumeration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Iterator & Enumeration" Watch "Iterator & Enumeration" New topic

Iterator & Enumeration

Shyam Hai
Ranch Hand

Joined: Feb 04, 2009
Posts: 68

what is the difference between

Iterator & Enumeration..

Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Ragavendran Sivaji Rao wrote:
what is the difference between

Iterator & Enumeration..


In Java 5 and above you have use foreach loop on anything that implements Iterable:

for (Object o : list) {

You can iterate over an Enumeration even it does not implement Iterable.

Iterable is a factory method for Iterator. Enumeration is similar to Iterator, and only maintains state for a single enumeration. So, be careful trying to wrap an Enumeration as an Iterable. If someone passes me an Iterable, I will assume that I can repeatedly call iterator on it, creating as many Iterators as I want, and iterating independently on each. A wrapped Enumeration will not fulfill this contract; don't let your wrapped Enumeration escape from your own code.
Enumeration is like an Iterator, not an Iterable. A Collection is Iterable. An Iterator is not.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45251
Have you read the API documentation for Enumeration and Iterator?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20175

There are two major differences between the Enumeration and Iterator interfaces:
- Iterator has a remove() method
- the names of the methods in Iterator are a lot shorter

For the rest, they are quite the same, also in use: while there are more elements, get the next element and handle it. In code:

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Iterator & Enumeration
It's not a secret anymore!