Collection Framework - Cursors in Java

Java provides interfaces that are implemented by collection classes so that we can fetch elements one by one or iterate through the elements in the collection.

The cursors provided by Java are :
1. Enumeration
2. Iterator
3. ListIterator
4. SplitIterator(introduced in Java 8)

Before the introduction of cursors, what was the way we used to iterate through the collection? The traditional for loop!!!

for(int i=0; i< coll.size;i++) {
     System.out.println(coll.get(i));
}

Enumeration
It is a legacy interface that provides us the facility to traverse through the elements of the legacy classes one by one.

The example for enumeration can be found here

Iterator
Enumeration has 2 limitations :
1. Its only applicable to legacy classes
2. We do not have an option to remove element from collection while traversing

The above two limitations were overcome by introduction of Iterator. Iterator is a universal cursor i.e. it is applicable to all the classes in the collection framework.

The example for iterator can be found here

ListIterator
While iterator gave us the facility to remove the elements while traversing, it still doesnt provide you with traversing backward or to previous element. Similarly, you cannot add/set elements.

With ListIterator, you get this options but only with classes that implement the List interface.

ListIterator, in addition to hasNext() and next() methods, provides hasPrevious(), previous(), add(), set() methods.

The example for listiterator can be found here


Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Hashed data structures