1. Iterator:
The Iterator interface was introduced in Java 1.2 as part of the Java Collections Framework. It provides a universal way to iterate over elements in various collection classes (also check how to remove objects from collection using itrator ), such as ArrayList, LinkedList, and HashSet. Key characteristics of an Iterator include:
- Forward-only traversal: Iterators allow traversing elements in a forward-only manner, from the beginning to the end of the collection.
- Removal of elements: Iterators support safe removal of elements during iteration using the remove() method.
- Enhanced functionality: Iterators offer additional methods like hasNext() to check if there are more elements, and next() to retrieve the next element in the iteration.
Example usage of an Iterator:
javaArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Alice");
names.add("Mike");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
The Enumeration interface was present in Java prior to the introduction of the Iterator interface. It is considered a legacy interface and is primarily used with older collection classes, such as Vector and Hashtable. Key characteristics of an Enumeration include:
- Read-only traversal: Enumerations provide read-only access to elements in a collection, allowing traversal from the beginning to the end.
- Limited functionality: Enumerations have a limited set of methods, including hasMoreElements() to check if there are more elements, and nextElement() to retrieve the next element in the enumeration.
Example usage of an Enumeration:
javaVector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
Enumeration<String> enumeration = fruits.elements();
while (enumeration.hasMoreElements()) {
String fruit = enumeration.nextElement();
System.out.println(fruit);
}
Key Differences:
- Legacy vs. modern: Iterator is part of the Java Collections Framework introduced in Java 1.2, while Enumeration is a legacy interface used with older collection classes.
- Functionality: Iterators provide additional functionality such as safe removal of elements, while enumerations offer a limited set of methods for read-only traversal.
- Fail-fast behavior: Iterators are designed to detect concurrent modification during iteration and throw a ConcurrentModificationException if the collection is modified. Enumerations do not provide this fail-fast behavior.
No comments:
Post a Comment