It’s very important to understand the fundamental of both the
interface for interview point of view or for work assignment aspect. Where should you use which interface? you can say most of the time you get encountered this question in interview which one should be used where?
Both of the
interface used to traverse the added Element from the collection during traversal in java. you know , both the interface is the key interface in java. As you know,
Enumeration is read-only, so it does not allow you to remove Element from collection, in fact you can say, not
remove() method in Enumeration interface.
Let us try to understand each of them one by one and then move to similarity and differences between them.
Enumeration is older
interface since jdk 1.0 , which is being used to traverse the item added in the collection.
Enumeration does not allow you to remove item added in the collection, as this is read-only. Key methods are:
Iterator interface is added later , you can say , this is improved version of
Enumeration. Whenever you required to remove item from collection while iterating you can use this interface. this is more safe and secure than
Iterator allow you to remove element from collection . Key methods:
hasNext() : this returns true if item present in the next cursor position.
next() : it returns Element added in next cursor position.
Enumeration VS Iterator
Enumerationis older since JDK 1.0 and
Iteratorintroduced in JDK later.
- functionality of
Iteratoris duplicated from
Iteratoris more secure and safe compared to
Enumeration, because of thread safe, it means,
Iteratordoes not allow
remove()method has been added in
Iteratorto make it immutable it means
- name of method in
Iteratoris shorter than
next() remove()while name of
Enumerationcan be used whenever you want Read-only
Usage of Enumeration and Iterator
This is very important which one should be used where, this is the gist of the topic. There are two different aspect. first, as you know
Iterator is improved version of
Enumeration, so you should use
Iterator always. second, Enumeration is read-only, so when you simply iteration is required not removal of item, then
Enumeration should be used.
Suggestions are welcome, to improve this topic, please write comment by sharing your thought.