Iterators In Java

Java Programming Java 8Object Oriented Programming

Iterators are used to traverse through the Java collections. There are three types of iterators.

  • Enumeration − Enumeration is initial iterators introduced in jdk 1.0 and is only for older collections like vector or hashTables. Enumeration can be used for forward navigation only. Element can not be removed using Enumeration.

  • Iterator − Iterator is a universal iterator introduced in Jdk 1.2 and can be used for any collections. Iterator can b e used for forward navigation only. Element can be removed using iterator if remove method is supported.

  • ListIterator − ListIterator is a iterator for List type collections and supports bidirectional navigation.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

public class Tester{

   public static void main(String[] args) throws ClassNotFoundException {
      Vector<Integer> vector = new Vector<>();
      vector.add(1);vector.add(2);vector.add(3);
   
      System.out.println("Vector: ");
      Enumeration<Integer> enumeration = vector.elements();
      while(enumeration.hasMoreElements()){
         System.out.print(enumeration.nextElement() + " ");
      }

      List<Integer> list = new ArrayList<Integer>();
      list.add(1);list.add(2);list.add(3);

      System.out.println("\nList: ");
      Iterator<Integer> iterator = list.iterator();
      while(iterator.hasNext()){
         System.out.print(iterator.next() + " ");
      }

      System.out.println("\nList using ListItertor (Forward): ");
      ListIterator<Integer> listIterator = list.listIterator();
      while(listIterator.hasNext()){
         System.out.print(listIterator.next() + " ");
      }
      System.out.println("\nList using ListItertor (Backward): ");
      while(listIterator.hasPrevious()){
         System.out.print(listIterator.previous() + " ");
      }
   }
}

Output

Vector:
1 2 3
List:
1 2 3
List using ListItertor (Forward):
1 2 3
List using ListItertor (Backward):
3 2 1
raja
Published on 19-Sep-2018 09:36:30
Advertisements