Iterator Example in Java

By | December 26, 2010
Iterator Example in Java Collection Framework. This Java Iterator example describes the basic operations performed on the Iterator in Collection Framework.
Iterator Example in Java Collection Framework. This Java Iterator example describes the basic operations performed on the Iterator in Collection Framework.

Program:

import java.util.*;
class IteratorDemo{
public static void main(String args[]){
ArrayList al=new ArrayList();
System.out.println(“Initial Size : ” + al.size());
al.add(“C”);
al.add(“A”);
al.add(“E”);
al.add(“B”);
al.add(“D”);
al.add(“F”);
System.out.println(“Original Contents of al : “);
Iterator itr=al.iterator();
while(itr.hasNext()){
Object element=itr.next();
System.out.print(element + ” “);
}
System.out.println();
ListIterator litr=al.listIterator();
while(litr.hasNext()){
Object element=litr.next();
litr.set(element + “+”);
}
System.out.println(“Modified Contents of a1 : “);
itr=al.iterator();
while(itr.hasNext()){
Object element=itr.next();
System.out.print(element + ” “);
}
System.out.println();
//Display the list backwards
while(litr.hasPrevious()){
Object element=litr.previous();
System.out.print(element + ” “);
}
System.out.println();
}
}

Result:

Initial Size : 0
Original Contents of al :
C A E B D F
Modified Contents of a1 :
C+ A+ E+ B+ D+ F+
F+ D+ B+ E+ A+ C+

Leave a Reply

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