In Java, Enumeration and Iterator are two interfaces that are used to traverse and manipulate collections. While they have similar functionality, there are some key differences between the two:
Type: Enumeration is an older interface that is only used with legacy classes, while Iterator is a newer and more versatile interface that can be used with any collection that implements the Iterable interface.
Direction: Enumeration can only be used to traverse a collection in forward direction, while Iterator can traverse a collection in both forward and backward directions.
Removal: Enumeration does not support the remove() method, while Iterator supports the remove() method to remove elements from a collection during iteration.
Thread-safety: Enumeration is not fail-fast and is not designed for use in concurrent environments, while Iterator is fail-fast and is designed for safe use in concurrent environments.
Here’s an example of how to use Enumeration and Iterator in Java:
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class Example {
public static void main(String[] args) {
// create a Vector of strings
Vector<String> myVector = new Vector<>();
myVector.add("apple");
myVector.add("banana");
myVector.add("orange");
// create an ArrayList of strings
ArrayList<String> myList = new ArrayList<>();
myList.add("apple");
myList.add("banana");
myList.add("orange");
// use Enumeration to traverse the Vector
Enumeration<String> myEnum = myVector.elements();
while (myEnum.hasMoreElements()) {
System.out.println(myEnum.nextElement());
}
// use Iterator to traverse the ArrayList and remove an element
Iterator<String> myIterator = myList.iterator();
while (myIterator.hasNext()) {
String element = myIterator.next();
System.out.println(element);
if (element.equals("banana")) {
myIterator.remove();
}
}
// print out the contents of the ArrayList after removing an element
System.out.println(myList);
}
}
In this example, we create a Vector of strings called "myVector" and an ArrayList of strings called "myList". We then use Enumeration to traverse the Vector and Iterator to traverse the ArrayList, and use the remove() method to remove an element from the ArrayList during iteration.
The output of this program would be:
apple
banana
orange
apple
banana
[apple, orange]
As you can see, both Enumeration and Iterator were used to traverse the collections, but Iterator was also used to remove an element from the ArrayList during iteration.
In summary, Enumeration and Iterator are two interfaces used for traversing and manipulating collections in Java, but they have some key differences in terms of type, direction, removal, and thread-safety. Which one to use depends on the specific use case and requirements of your program. However, Iterator is generally preferred due to its versatility and thread-safety.