Monday, 13 July 2015

Iterator vs Enumeration


Enumeration
Iterator
JDK
JDK1.0 in java.lang package
JDK 1.2 in java.util package
Remove elements
Not allowed
remove() method do this for us.
Read-only
Yes
No
Thread-safe

More secure and safe because it does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException.
Methods
hasMoreElement()
nextElement()

Read-only interface.
hasNext()
next()
remove()

EnumIteration.java
import java.util.*;
public class EnumIteration {
       public static void main(String[] args){
              Vector v=new Vector();
              Object element;
              Enumeration enm;
              Iterator iter;
              long start;

              for(int i=0; i<1000000; i++){
                     v.add("New Element");
              }

              enm=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

              //request to GC to free up some memory
              System.gc();

              //CODE BLOCK FOR ENUMERATION
              start=System.currentTimeMillis();
              while(enm.hasMoreElements()){
                     element=enm.nextElement();
              }
              System.out.println("Enumeration took"+
                                (System.currentTimeMillis()-start));
              //END OF ENUMERATION BLOCK
       }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...