Iterator in Java
Iterator interface in Java is using to Iterate objects in collections. Before the inclusion of Iterator in Java , Enumeration was there to do iterations in collections .
Enumeration Vs Iterator
Both are interfaces in Java for iterating data in a collections .Iterator is the improved version of Enumeration.The method names are shorter in case of Iterator.And one remove() method has been added in Iterator interface.
Methods in Iterator
1) boolean hasNext()
2) E next()
3) void remove()
Methods in Enumeration
1)boolean hasMoreElements()
2)E nextElement()
Now let us see an example . Here we have an ArrayList object. We are adding few String values to it in addItems() method.The displayItems() method iterates the contents of the ArrayList.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorSample { List list = null; Iterator iterator = null; public IteratorSample() { list = new ArrayList(); } public void addItems() { list.add("cat"); list.add("dog"); list.add("cow") ; } public void displayItems() { iterator = list.iterator(); System.out.println("Iterating the list"); while(iterator.hasNext()){ System.out.println(iterator.next().toString()); } } public static void main(String[] args) { IteratorSample sample = new IteratorSample(); sample.addItems(); sample.displayItems(); } }
Output
Iterating the list
cat
dog
cow
So this verifies the concept of Iterator.Other collections like Set also can be iterated in the same way.
Iterator Vs ListIterator
ListIterator interface is an enhancement of Iterator interface. If we are using Iterator for iterating the collection ,then iteration can be done only in one direction. But in the case of ListIterator iteration in both directions are possible.The additional methods in ListItertor are listed here:
1. boolean hasPrevious()
2.E previous()
3. int nextIndex()
4.int previousIndex()
5. void set(E e)
6.void add(E e)
So there are total 9 methods in ListIterator interface.Of these 9 , 6 are added in ListIterator and 3 are from extending Iterator.