Iterator:

  • We can apply Iterator concept for any Collection object, hence it is universal cursor.
  • By using Iterator we can perform both read and remove operations.
  • We can create Iterator object by using iterator() method of Collection interface.

    public Iterator iterator();
    //exa,
    Iterator it=c.iterator();
    //where c is any Collection object

Methods:

Iterator interface defines the following three methods:

public booleanhasNext()
public Object next()
public void remove()

let's see a simple example for better understanding:

IteratorDemo.java:

importjava.util.*;
classIteratorDemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
for(inti=0;i<=10;i++)
{
al.add(i);
}
System.out.println(al);
Iterator it=al.iterator();
while(it.hasNext())
{
Integer i=(Integer)it.next();
if(i%2==0)
System.out.println(i);
else
it.remove();
}
System.out.println(al);
}
}

Output

[0,1,2,3,4,5,6,7,8,9,10]
0
2
4
6
8
10
[0,2,4,6,8,10]

Limitations :

  • By using Enumeration and Iterator, we can move only forward direction and we can?t move to the backward direction, hence these are the single direction cursors.
  • By using Iterator we can perform only read and remove operations and we can?t perform replacement of new objects.
  • So to overcome these limitations of Iterator, we should go to ListIterator.
Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

Silansoftware Pvt.Ltd, BBSR
Call to: 0674-2361252

Comment