Saturday, 4 May 2013

Understanding Iterators in Java

Having some idea about Collections in Java lets see what is an Iterator and what is it used for? As described in post on Java Collection an Iterator object is used to iterate over elements stored in a Collection.

 You know that Collection is an Interface. Even List, Set, Queue are Interfaces which then have their own concrete implementations like ArrayList, HashSet, LinkedList etc. Collection Interface implements another Interface called Iterable.

If you go and open the sour code for Collection Interface in Java you will find -

public interface Collection<E> extends Iterable<E> 

{

 int size();

 boolean isEmpty();

 boolean contains(Object o);

 Iterator<E> iterator();

 Object[] toArray();

 <T> T[] toArray(T[] a);

 boolean add(E e);

 boolean remove(Object o);

 boolean containsAll(Collection<?> c);

 boolean addAll(Collection<? extends E> c);

 boolean removeAll(Collection<?> c);

 boolean retainAll(Collection<?> c);

 void clear();

 boolean equals(Object o);

 int hashCode(); 
} 

and if you go and see what there in Iterable Interface you will find -

public interface Iterable<T> 
{
    Iterator<T> iterator();
}


Iterator is again an interface whose source code is as follows -

public interface Iterator<E> 
{
    boolean hasNext();
    E next();
    void remove();
}


Note :  All these are just Interfaces(abstract functions). Their concrete implementation will be in the first concrete subclass.

Points to Note -
  • We can iterate only in one direction.
  • Iteration can be done only once. This means once we reach end of a series we must get a new iterator to iterate. 

Lets take an example to demonstrate how Iterator works -

package testCodes;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

    public static void main(String[] args) {
       
        List<String> nameList = new ArrayList<String>();
        nameList.add("John");
        nameList.add("Sam");
        nameList.add("kenny");
        nameList.add("Jessica");
       
        Iterator<String> namesIterator = nameList.iterator();
        System.out.println("Printing names");
        while(namesIterator.hasNext())
        {
            System.out.println(namesIterator.next());
        }
    }

}




 Output

Understanding the code

    First we create a ArrayList called nameList and store some values in it. Note the use of Generics. nameList will and should always contain a String. If you try to add any other object Compiler will complaint. Also when you extract any element from the List you will always get a String object.

     Next we get an Iterator from the ArrayList. Note the Syntax. We can get such Iterator from any entity(interface/class) which come under Collection inheritance tree(Remember Collection implements Iterable). So we just need to use .iterator() function to get the respective iterator. Then we can iterate to get the elements. Note .hasNext() checks whether Collection(List/ArrayList in our case) has next element or not where as .next() will actually give you the next element.

Note :  Map and its sub classes/ sub interfaces are not a part of Collections.So you cannot use .iterator() function on it. There are other was to iterate over it's data but we shall cover that separately.

No comments:

Post a Comment

t> UA-39527780-1 back to top