Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

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.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext