What is the difference between iterator and enumeration
This is the one major difference between Enumeration and Iterator in java. You can say Iterator is some what advanced version of Enumeration. Iterator interface is introduced from JDK 1. This is the main difference between Enumeration and Iterator interface. Enumeration only traverses the Collection object. Where as Iterator interface allows us to remove an element while traversing the Collection object. Iterator has remove method which is not there in the Enumeration interface.
Below is the list of Enumeration and Iterator methods. Enumeration is a legacy interface used to traverse only the legacy classes like Vector , HashTable and Stack.
Where as Iterator is not a legacy code which is used to traverse most of the classes in the collection framework. Iterator is a fail-fast in nature. Where as Enumeration is fail-safe in nature. Here is the note from the Enumeration Docs.
The while loop calls the hasNext method. It returns true if there are more elements in the collection. It returns false if there are no further elements to traverse. Inside the loop, the next method helps to obtain every element in the collection. Likewise, itr reads and displays the elements in the collection. In line 21, the itr removes the last element, which is three, from the collection.
Finally, the remaining elements, which are one and two, display on the console. Enumeration is an interface that allows obtaining one element at a time in a collection of objects. Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector. Figure 2: Java program with Enumeration. In the above program, days is of type Enumeration. The dayNames is an object of Vector. The add method helps to add elements to the Vector.
Get Free Tutorials by Email Email:. Advertisements help running this site for free. To view the content please disable AdBlocker and refresh the page. Iterator allows to remove elements from the underlying collection during the iteration using its remove method. Iterator is a fail-fast in nature.
0コメント