Iterator in java.

Iterator in java.

Posted in : Core Java Posted on : January 24, 2011 at 3:39 PM Comments : [ 0 ]

Here, we will introduce about the iterator interface of java collection framwork.

Iterator in java.

An Iterator is a process of traversing through all the elements in a container or list. There is no matter in which order elements are arranged. An Iterator iterate through the elements sequentially. 

Definition of an Iterator 

In computer science Iterator is defined as an object that allows traversing over all the elements of collection in a sequence. It is a process of cycling through the elements in a collection. Some times in the context of database it is called a cursor.


An Iterator object is implemented by the following two interfaces : 

1. public interface Iterator<E>

2. public interface ListIterator<E>

Parameter Description 

E : It is the type of elements backed by this iterator. 

Example of implementation of the above both interfaces

In this example we will show you only how the above two interfaces can be implemented. You can see more example of these interfaces with their methods individually in next section. Through this example we will show you how can these interfaces are instantiated and how they iterate with their methods.


import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
public class IteratorAndListIterator {
  public static void main(String args[]) {
    ArrayList alist = new ArrayList();
    // Implementation of Iterator
    Iterator<Integer> itr = alist.iterator();
    System.out.println("First element of arrayList =";
    System.out.println("Second element of arrayList =";
    System.out.println("Third element of arrayList =";    
    LinkedList llist = new LinkedList();
    // Implementation of ListIterator
    ListIterator<Integer> litr = llist.listIterator();
    System.out.println("\nFirst element of linkedList =";
    System.out.println("Second element of linkedList =";
    System.out.println("Third element of linkedList =";

Output : 

First element of arrayList =1
Second element of arrayList =2
Third element of arrayList =3
First element of linkedList =4
Second element of linkedList =5
Third element of linkedList =6

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics