The methods used by
Iterator
are:
- 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
:
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 + " ");
}
}
}
OUTPUT10 20 30 40 50
..................
10 20 40 50
DESCRIPTIONThis 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
.