Enumeration vs iterator


Enumeration vs iterator

Iterator and Enumeration allows iterate elements of collections in Java, There is some major difference. Iterator have a remove() method allows you to remove elements from collection during traversing but Enumeration doesn't allow that, it doesn't have the remove() method. Enumeration is also a legacy class introduce in JDK1.0 and not all Collection supports it. Vector supports Enumeration but ArrayList doesn't.



Differences between enumeration and iterator

1- One of the major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't have any method to remove element. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects of collection(vector). On the ohter side Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.


2- Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

 

In short both Enumeration and Iterator will traverse and fetch the elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. It is a short difference:

 

Enumeration mehtods

1. it is use for only lagacy class(eg. Vector)

    Enumeration e = v.elements();  
    v is the object of `Vector` class

2. Read operation can be perform, we can not remove element.
3. Two Method are available

  • public boolean hasNextElement();
  • public Object nextElement();

Iterator

  1. it is applicable for all Collection

    Iterator itr = c.iterator();  
    where c is any `Collection` class
  2. Read and Remove operation can be perform

  3. Three Method are available

    • public boolean hasNext();
    • public Object next();
    • public void remove();

Limition in both

  • Move only forward direction
  • There is no any methods for Add object and Replace object

So Enumeration is used when ever we want to make Collection objects as Read-only.

 

Related Articles

post a comment