Skip to main content

Difference between Enumeration and Iterator

Use Iterator always for better programming.

One big difference between Iterator and Enumeration is (apart from what Pallav has already mentioned), iterator is fail-safe. If you are using an iterator to go through a collection you can be sure of no concurrent modifications in the underlying collection which may
happen in multi-threaded environments.



Well, apart from being an advantage this also is said to decrease performance by a tad. However, that's negligible. (Some amount of processing is involved in checking for modifications). If you see the docs it says about "well defined semantics" for the iterator, the fail-safe property adds to that.


Enumeration and Iterator are interfaces in java.util package.
Enumeration is the old Interface(for legacy classes like Hashtable).
Iterator is for the new classes like HashSet,HashMap..
Enumeration and Iterator are used to just count the no of elements and view it.
But Iterator has an additional method for deleting elements.
So when you intend to delete elements. you can go for the Iterator Interface.




All of the above are correct but we have forgotten about one thing - iterator is a design pattern and the purpose is to abstract looping. For example you have a class that loops thru Lists or ArraysLists so you used Enumeration. But suddenly another programmer made an Array (say String[]) that can only do for loop. Your enumeration is screwed I would say. So the strategy is to use Iterator. Now first you will have this method in your 
class:


//this is Loop.java
public void loopThis(Iterator iter){
while(iter.hasNext()){
Object obj = iter.next();
}
}

So you use it this way:
Loop loop = new Loop();
ArrayList daList = new ArrayList();
loop.loopThis(daList.keys().iterate());

Now this part is to show you haw to make an iterator out of a String[]
1. Make an Iterator Class
public class CustomIterator implements java.util.Iterator{
String[] arry;
int rowPosition = 0;
int lngth = 0;

public CustomIterator(String[] arry){
this.arry = arry;
this.lngth = arry.length;
}

public boolean hasNext(){
if(rowPosition >= lngth) return false;
else return true;
}

public Object next(){
Object obj = arry[rowPosition];
rowPosition++;
return obj;
}

public void remove(){
for(int i = rowPosition-1; i < (lngth -1); i++){
arry[i] = arry[i+1]; // move up data
}
arry[lngth-1] = null;
lngth--;
rowPosition--;
}
}

and here is how you do it:
Loop loop = new Loop();
ArrayList daList = new ArrayList();
loop.loopThis(daList.keys().iterate());

String[] str = new String[]{"1","2","3","4","5"};
CustomIterator iter = new CustomIterator(str);
loop.loopThis(iter);



Well, not really. What if I implement the iterator design pattern using the enumeration interface? The Iterator design pattern does'nt make it mandatory to implement a remove method. All it says is to give a iteration capability irrespective of the underlying collection. I'll make Custom Iterator implement Enumeration without the remove method. Now we've implemented the iterator design pattern using enumeration and the enumeration works fine. The eponymous iterator interface may have derived its name from the iterator pattern but does'nt mean that an Enumeration can use the iterator design pattern.

Comments

  1. The functionality of Enumeration interface is duplicated by the Iterator interface.
    Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. I have also blogged about
    difference between iterator and enumeration here.

    ReplyDelete

Post a Comment

Popular posts from this blog

Asynchronous Vs. Synchronous Communications

Synchronous (One thread):   1 thread -> |<---A---->||<----B---------->||<------C----->| Synchronous (multi-threaded):   thread A -> |<---A---->| \ thread B ------------> ->|<----B---------->| \ thread C ----------------------------------> ->|<------C----->|

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol