Menu
Topics Index
...
`

IteratorDemo - Java Example Program


IteratorDemo
import java.util.*;

class IteratorDemo
{
    public static void main(String arg[])
    {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);
        Iterator<Integer> itr = numbers.iterator();
        while (itr.hasNext())
        {
            int number = itr.next();
            System.out.print(number + " ");
            if (number == 30)
                itr.remove();
        }
        System.out.println("\n..................");
        itr = numbers.iterator();//LINE A
        while (itr.hasNext())
        {
            int number = itr.next();
            System.out.print(number + " ");
        }        
    }
}
OUTPUT

10 20 30 40 50
..................
10 20 40 50

DESCRIPTION

This example explains all the 3 methods of iterator. The first while loop displays all the elements of the list num and it comes out of the loop when the iterator has no next element. It also removes element 30 from the list num. The second while loop displays the elements after removing 30 from the list num.

THINGS TO TRY
  • Try this program by removing LINE A. The output is as shown below.
    10 20 30 40 50
    ..................

    The condition in the second while loop will become false, since there is no next element. That is because in the previous while loop the end of the list is reached. If we call hasNext at the end. it will return false.
  • Place the below shown code in the above program and check the output.
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(10);
    Iterator<Integer> itr = numbers.iterator();
    while (itr.hasNext()) {
        int number = itr.next();
        itr.remove();
        System.out.print(number + " ");
    }
    System.out.println(numbers.size());
    Remember hasNext becomes true if the list has atleast one element. So the output of the above code will be 10.

© meritcampus 2019

All Rights Reserved.

Open In App