Junior — Middle
What is the difference between an enumerator and an iterator in Java?
sobes.tech AI
Answer from AI
Enumerator (Enumeration) and Iterator are interfaces for traversing collections in Java, but there are differences between them:
- Enumeration is an outdated interface that appeared in early versions of Java. Methods: hasMoreElements() and nextElement(). It does not support element removal.
- Iterator is a more modern interface introduced in Java 1.2. Methods: hasNext(), next(), and remove(). It allows safe removal of elements during traversal.
Example of using Iterator:
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("a")) {
it.remove();
}
}