Iterators In Java

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.


 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<>();
      System.out.println("Vector: ");
      Enumeration<Integer> enumeration = vector.elements();
         System.out.print(enumeration.nextElement() + " ");

      List<Integer> list = new ArrayList<Integer>();

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


1 2 3
1 2 3
List using ListItertor (Forward):
1 2 3
List using ListItertor (Backward):
3 2 1

Updated on: 23-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started