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

Java Health Center - Overview and Features

This video highlights the features available in Health Center. Health Center is a low-processor and memory usage diagnostic tool for monitoring the status of a running IBM Java Virtual Machine (JVM). Health Center provides live information and recommendations in each of the following areas: - Classes: information about classes being loaded - Environment: details of the configuration and system of the monitored application - Garbage Collection: information about the Java heap and pause times - Locking: information about contention on inflated locks - Profiling: sampling profile of Java methods including call paths

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...

Java Garbage Collection

Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic pro...