Difference between Iterator and Enumeration in java

In this post, we will see the difference between Iterator and Enumeration in Java. First, we will see Iterator vs Enumeration in brief later we will see some points in details.

Enumeration Iterator
Enumeration interface introduced in java 1.0 as is legacy interface.Iterator interface introduced in java 1.2.
Enumeration is used to traverse only legacy classes(legacy classes are those classes which introduced initial days of java like vector,hashtable etc)Iterator is used to traverse all types of collections.
In case of Enumeration we can not do any modification in collection.In case of Iterator we can remove the element from collection.
Enumeration has two method hasMoreElements() and nextElements().Iterator has three method hasNext(), next() and remove().
methods name are bigger than Iterator methods.Iterator has shorter method names.

 

Example of Iterator –

import java.util.*;
public class ArraListExample {
 
	public static void main(String[] args) {
 
		List<String> listObject = new ArrayList<>();
 
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
 
		// iterator() is a method defined in List interface
		// Iterator is a interface.
		// it is reference of Iterator interface
		Iterator it = listObject.iterator();
 
		// it.hasNext() will check, next element is there or not if yes while
		// loop will execute.
		while (it.hasNext()) {
 
			// it.next() will print all element one by one
			System.out.println(it.next());
 
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Example of Enumeration –

 

package iteratorandlistitearator;
import java.util.*;
public class Example {
public static void main(String[] args) {
	Vector<String> vectorObject = new Vector<>();
	 
	vectorObject.add("suresh");
	vectorObject.add("mohan");
	vectorObject.add("shyam");
	vectorObject.add("mohan");
	vectorObject.add("ram");

	
	Enumeration e = vectorObject.elements();

	while (e.hasMoreElements()) {

		System.out.println(e.nextElement());

	}
	
	
	
	
	
}
}

Output is –

suresh
mohan
shyam
mohan
ram

That’s all about Difference between Iterator and Enumeration in java.

You may like.

Iterator docs.

Enumeration docs.