In this article, we will compare 3 important cursors Enumeration, Iterator & ListIterator in detail i.e.; Enumeration v/s Iterator v/s ListIterator interfaces. All 3 cursors are used to iterate over collection items, but there are certain differences between each one of them
So lets us discuss in Details;
Enumeration vs Iterator vs ListIterator
Enumeration |
Iterator |
ListIterator |
This is part of Legacy collection introduced in Java 1.0 version | This is part of Collection framework introduced in Java 1.2 version | This is part of Collection framework introduced in Java 1.2 version |
Using Enumeration interface, we can enumerate only legacy classes like Hashtable or Vector or Properties | Iterator interface is applicable for every collection classes like ArrayList, HashSet or Hashtable | ListIterator interface is applicable only for List objects like ArrayList or LinkedList or Vector |
We can enumerate legacy collection items only in a FORWARD direction | Here, too we can iterate through collection items only in a FORWARD direction | But with ListIterator, we can iterate through list items either in Forwarding or BACKWARD directions |
That is, it is a unidirectional or single-directional cursor | That is, it is a unidirectional or single-directional cursor | That is, it is a bi-directional cursor |
Using Enumeration interface, we can enumerate to read or get element/object from a legacy collection | Using Iterator interface, we can read as well as remove collection items, while iterating | Addition or replacement of new objects is possible alongside reading and remove operation in ListIterator interface |
To get an Enumeration object, we can use elements() method of any legacy collection class example,
Vector v = new Vector(); | To get an Iterator object, we can use iterator() method of any collection class example,
Iterator it = col.iterator(); | To get a ListIterator object, we can use listIterator() method of any List classes for example,
ListIterator ltr = list.listIterator(); |
This interface has 2 important methods to enumerate through the legacy collection object:
| Iterator interface has 3 important methods to iterate through any collection object boolean
| ListIterator interface has 9 important methods to iterate through any
|
Best practice:
Enumeration interface:
- Use this cursor only with a legacy collection, to work with a thread-safe environment
Iterator interface:
- This is very popular among 3 cursors, as it is applicable for any collection class
ListIterator interface:
- Again, this is applicable only for List objects.
- Use this cursor, to benefit from iterating through List items in both directions
- i.e.; both FORWARD & BACKWARD directions