0% found this document useful (0 votes)
10 views3 pages

It Erator

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

It Erator

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

2) Iterator:

 We can Use Iterator to get Objects One by One from Collection.


 We can Apply Iterator Concept for any Collection Object. Hence it is Universal
Cursor.
 By using Iterator we can Able to Perform Both Read and Remove Operations.
 We can Create Iterator Object by using iterator() of Collection Interface.

public Iterator iterator();


Eg:Iterator itr = c.iterator(); //c Means any Collection Object.

Methods:
1) public boolean hasNext()
2) public Object next()
3) public void remove()

Example :

package list;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class ArrayListDemo {

public static void main(String[] args) {

ArrayList al = new ArrayList();


al.add(11);
al.add(22);
al.add("Santosh");
al.add(11);
al.add("Bikkad");
al.add("Pune");
al.add("Santosh");

System.out.println(al);

Iterator iterator = al.iterator();

while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}

}
}

Example :

package list;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class ArrayListDemo {


public static void main(String[] args) {

ArrayList al = new ArrayList();


al.add(11);
al.add(22);
al.add("Santosh");
al.add(11);
al.add("Bikkad");
al.add("Pune");
al.add("Santosh");

System.out.println(al);

Iterator iterator = al.iterator();

while (iterator.hasNext()) {
Object next = iterator.next();

if (next.equals("Bikkad")) {
iterator.remove();
}
}
System.out.println(al);
}
}

Example :

package list;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class ArrayListDemo {

public static void main(String[] args) {

ArrayList al = new ArrayList();


al.add(11);
al.add(22);
al.add("Santosh");
al.add(11);
al.add("Bikkad");
al.add("Pune");
al.add("Santosh");

System.out.println(al);

for(Object a:al) {
System.out.println(a);
}
}
}
Limitations:
 By using Enumeration and Iterator we can Move Only towards Forward Direction and
we
can’t Move Backward Direction. That is these are Single Direction Cursors but Not
Bi-
Direction.
 By using Iterator we can Perform Only Read and Remove Operations and we can't
Perform
Addition of New Objects and Replacing Existing Objects.
To Overcome these Limitations we should go for ListIterator.

You might also like