Both Enumerator and Iterator provides a way to traverse/navigate/iterate through a collection.
Enumerator is there in java since early age i.e JDK1.0 and Iterator was introduced in JDK1.2 with collections.
Iterator is more secure and safe as compared to enumeration because if some other thread wants to modifies the same collection concurrently, Iterator throws CocurrentModificationException.
Iterator interface is a duplicate copy of Enumerator interface while providing extra feature to remove elements.
Below code explains about traversal of ArrayList collection using both :
Enumeration :
List myList = new ArrayList();
myList.add("Hello");
myList.add("World");
myList.add("New");
myList.add("Example");
Enumeration enums = Collections.enumeration(myList);
while (enums.hasMoreElements())
System.out.println("" + enums.nextElement());
Iterator :
List myList = new ArrayList();
myList.add("Hello");
myList.add("World");
myList.add("New");
myList.add("Example");
Iterator iterator = myList.iterator();
while (iterator.hasNext())
System.out.println("" + iterator.next());
Note:
- Iterators allows to safe removal of elements from the collection during the iteration by using remove method of Iterator (not by collection's remove method) . Enumeration does not have remove method.
- Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time.
- Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration, b’ coz it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly.
- Before using iterator.remove(), the Iterator should point to any of its elements.
The remove() removes the element which the Iterator correctly pointing to
Otherwise it will throw IllegalStateException
No comments:
Post a Comment