What are the differences between Iterator and Enumeration? Core Java Collections Interview Question
ANS) Both Iterator and Enumeration are used to iterate the elements from the Collections.Below are the some of the differences between iterator and enumeration :
Iterator | Enumeration |
The Iterator is slower than Enumeration. | Enumeration is faster than Iterator. |
The Iterator is fail-fast. | Enumeration is not fail-fast. |
It throws ConcurrentModificationException if a Collection is modified while iterating other than its own remove() method. | It does not throw ConcurrentModificationException if Collection is modified during the traversal. |
The Iterator can traverse legacy and non-legacy elements. | Enumeration can traverse only legacy elements. |
Iterator is not a legacy interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet . | Enumeration is a legacy interface which is used for traversing Vector, Hashtable. |
Iterator has hasNext(),next() and remove() methods | Enumeration has hasMoreElements() and nextElement() methods |
The Iterator can perform remove operation while traversing the collection. | The Enumeration can perform only traverse operation on the collection. |
There are couple of similarities between Iterator and Enumeration in Java
Interface : Both Iterator and Enumeration are interfaces.
Package : Both Iterator and Enumeration are present in java.util package.
What does Fail-fast Mean ?
The Iterator in java which immediately throws ConcurrentmodificationException, if any structural modification occurs in, is called as a Fail-fast iterator. Fail-fast iterator does not require any extra space in memory.
No comments:
Post a Comment
Hello Buddy, if you have any doubts or need any clarification , feel free to comment. Thanks.