1. Overview of Enumeration VS Iterator in Java
It’s very important to understand the fundamental of both the
interface for usability point of view and for interview point of view or for work assignment aspect. Where should you use which interface and for what operations? You can say most of the time you get encountered this question in an interview which one should be used where?
2. Enumeration vs iterator in Java
Both of the
interface used to traverse the added Element from the collection during traversal in java. 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, you can say, no
remove() method in Enumeration interface.
Let us try to understand each of them one by one and then move to similarity and differences between Enumeration and Iterator.
3. Enumeration in Java
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:
4. Iterator in Java
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 .
hasNext(): this returns true if item present in the next cursor position.
next(): it returns Element added in next cursor position.
5. Key points of Enumeration vs Iterator in Java
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
6. Differences between Enumeration and Iterator
- Enumeration used for read only operation, can’t modify at the time of traversing, while Iterator used for read and write both at the time if traversing
- Enumeration added in JDK 1.0 while Iterator added in JDK 1.2
- Enumearation is fail-safe while Iterator is fail-fast.
7. 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 aspects.
- As you know
Iteratoris improved version of
Enumeration, so you should use
- Enumeration is read-only, so when you simply iteration is required not removal of item, then
Enumerationshould be used.
Visit Oracle Java official Site for more details.
I hope enjoyed visit Core Java tutorial for more details.
Suggestions are welcome, to improve this topic, please write a comment by sharing your thought.