Iterator and Enumeration are Java cursors (Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object's elements one by one.). They belong to Java collection framework. Enumeration was added in JDK 1.0 and Iterator in the JDK.1.2 version in the collection framework.
The major difference between Enumeration and Iterator in java is that by using Enumeration, we can only traverse a Collection but by using Iterator, we can also remove an element while traversing the Collection.
Following is a list of differences between Iterator and Enumeration.
Iterator | Enumeration |
Iterator has three methods: hashNext(), next() and remove(). | Enumeration has two methods: hasMoreElements() and nextElement(). |
Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. | We cannot remove elements from a collection when using enumerator. |
Enumeration interface is there from JDK 1.0 | Iterator interface was introduced from JDK 1.2. |
Iterator is a fail-fast in nature. i.e, it throws ConcurrentModificationException if a collection is modified while iterating other than it's own remove() method. | Enumeration is fail-safe in nature. It doesn't throw any exceptions if a collection is modified while iterating. |
Iterator is considered safe because it is fail-fast in nature | If we want to modify object while iterating we should use Enumeration. |
Sample Java code to demonstrate Iterator and Enumeration
class EnumerationExample { public static void main(String args[]) { List list = new ArrayList(Arrays.asList( new String[] {"Apple", "Cat", "Dog", "Rat"})); Vector v = new Vector(list); delete(v, "Dog"); } private static void delete(Vector v, String name) { Enumeration e = v.elements(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equals(name)) { v.remove(name); } } // Display the names System.out.println("The names are:"); e = v.elements(); while (e.hasMoreElements()) { // Prints elements System.out.println(e.nextElement()); } } } class IteratorExample { public static void main(String args[]) { List list = new ArrayList(Arrays.asList( new String[] {"Apple", "Cat", "Dog", "Rat"})); Vector v = new Vector(list); delete(v, "Dog"); } private static void delete(Vector v, String name) { Iterator i = v.iterator(); while (i.hasNext()) { String s = (String) i.next(); if (s.equals(name)) { i.remove(); } } // Display the names System.out.println("The names are:"); i = v.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
Hope you have enjoyed reading Difference between Iterator And Enumeration in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp