Menu
Topics Index
...
`


Collections Framework > Iterator >
Siva Nookala - 03 Mar 2017
The Iterator helps you to move through all the elements in a collection.

The methods used by Iterator are:
MethodDescription
boolean hasNext()Returns true if the collection has next element, else it returns false.
E Next()Returns the next element. If there is no next element, it throws anexception.
void remove()Removes the current element to which the iterator is pointing.
  • We obtain the iterator to the start of theCollection by calling iterator() method.
For example, Iterator itr = num.iterator();

The following example illustrates all the methods of Iterator:
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.

Dependent Topics : Java ArrayList  Java LinkedList   java.util.Arrays - Class Arrays In Collection Framework 

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.