Tuesday, December 1, 2015

Java Collections - Difference Between Iterator And Enumeration With Example

Ref:- http://javahungry.blogspot.com/2013/06/difference-between-iterator-and-enumeration-collections-java-interview-question-with-example.html

Iterator

Iterator is the interface and found in the java.util package.
It has three methods

*hasNext()
*next()
*remove()

Enumeration

Enumeration is also an interface and found in the java.util package .
An enumeration is an object that generates elements one at a time. It is used for passing through a collection, usually of unknown size.
The traversing of elements can only be done once per creation.

It has following methods

*hasMoreElements()
*nextElement()

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework.

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.



import java.util.*;
public class Performance {
    public static void main(String[] args){
        Vector v=new Vector();
        Object element;
        Enumeration enum;
        Iterator iter;
        long start;
        
        for(int i=0; i<1000000; i++){
            v.add("New Element");
        }
        
        enum=v.elements();
        iter=v.iterator();
        //*****CODE BLOCK FOR ITERATOR**********************
        start=System.currentTimeMillis();
        while(iter.hasNext()){
            element=iter.next();
        }
        System.out.println("Iterator took " + (System.currentTimeMillis()-start));
        //*************END OF ITERATOR BLOCK************************
        
        System.gc();   //request to GC to free up some memory
        //*************CODE BLOCK FOR ENUMERATION*******************
        start=System.currentTimeMillis();
        while(enum.hasMoreElements()){
            element=enum.nextElement();
        }
        System.out.println("Enumeration took " + (System.currentTimeMillis()-start));
        //************END OF ENUMERATION BLOCK**********************
    }
}




*Why not use for(int i=0; i< v.size();i++){}?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:



int i = 0 is an assignment and creation (2 operations)
i get size, check value of i, and compare (3 operations)
i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
*7/8 operations in total, each time the loop runs through

where an enumeration or iterator uses a while(){}
while(v.hasNext()) has next true or false (1 operation)
while(v.hasMoreElements()) has more true or false (1 operation)
*Only one operation per repeat of this loop

No comments:

Post a Comment