Iterator in Java

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.


Iterating the list

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() 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.

See Related Discussions:

ListIterator in Java

Collections in Java

Threading in Java

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">