What is difference between Enumeration and Iterator interface

What is difference between Enumeration and Iterator interface

Answer : Below shows difference :

IteratorEnumeration
Iterate over collectionThis also iterate over collection
Method name made shorter (Method name has been imporoved)Method name was big
Added remove operation that allows to remove elements from collection during iterationNo functionality to remove element form collection
It has three method: hasNext(), next() and remove()It has two method hasMoreElements(),nextElement()

Please see example below:

package com.javahonk.iteratorenumeration;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class IteratorEnumerationTest {

	public static void main(String[] args) {

	List<String> arrayList = new ArrayList<String>();

	arrayList.add("Java");
	arrayList.add("Honk");

	// Iterator example
	System.out.println("Iterator example:");
	Iterator<String> iterator = arrayList.iterator();
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);

	}

	// Enumeration example although it's not
	// preferable
	System.out.println("\nEnumeration example:");
	Vector<String> vector = new Vector<String>();
	vector.add("Java");
	vector.add("Honk");
	Enumeration<String> enumeration = vector.elements();
	while (enumeration.hasMoreElements()) {
		String type = (String) enumeration.nextElement();
		System.out.println(type);

	}

	// Preferable: Use an enhanced for loop
	// to display contents.
	System.out.println("\nEnhanced iterator example:");
	for (String string : arrayList) {
		System.out.println(string);
	}

	}

}

 

Output:

What is difference between Enumeration and Iterator interface

Leave a Reply

Your email address will not be published. Required fields are marked *