Tuesday 23 June 2015

What is the Difference between Iterator and Enumeration in Java?

Both Iterator and Enumeration are Interfaces found in the java.util package and both are used for iterating elements of a collection. Collections such as ArrayList and Vector can be iterated and cycled through using Iterator or Enumeration Interfaces. But, there are also differences among both of these Interfaces. What are those differences?

Iterator:

Iterator is an Interface of a the Java Collections Framework and is used to cycle through elements to perform some logic or to display the elements. Iterator can also be used to check whether elements are present in a Collection or to remove the elements from the Collections. Iterator Interface has the following methods:

hasNext()
next()
remove()

Enumeration:

Enumeration is also an Interface from the Java Collections Framework and is used to cycle through elements to perform some logic or to display elements in the Collections like ArrayList. But, Enumeration Interface helps in enumerating the elements, i.e, get one element at a time from the Collections. Enumeration is considered as obsolete by the developers and Iterator is preferred over Enumeration. Enumeration Interface doesn't contain method to remove elements from the Collections. The following methods in Enumeration Interface are:

hasMoreElements()
nextElement()

The three differences between the two are:

  1. Naming has improved and is more appropriate now.
  2. remove() method is added to Iterator and Enumeration is considered as obsolete.
  3. Iterator is more secure when compared to Enumeration.
That's all. Hope you found it useful. Please let us know if anything you may need by commenting.