Pages

Iterator in java

What is Iterator in java?
  • Iterator is a universal cursor i.e., we can apply iterator concept for any collection object
  • By using an iterator, we can perform both Read and Remove operations
  • We can create iterator object by using iterator() method of Collection interface.
public Iterator iterator()

ex:: Iterator it=c.iterator(); where c is any collection object

Methods::
public boolean hasNext()
public Object next()
public void remove()

Demo on Iterator program:
import java.util.ArrayList;
import java.util.Iterator;

public class iterator {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(1);
l.add(3);
l.add(2);
l.add(5);
l.add(0);
Iterator Itr = l.iterator();
while (Itr.hasNext()) {
Integer I = (Integer) Itr.next();
if (I % 2 == 0) {
System.out.println(I);
} else {
Itr.remove();
}
}
System.out.println(l);
}
}
Output:
iterator program in java
iterator program in java


---> The main difference between enumeration and Iterator is:
By using enumeration we can get read access but by using Iterator we can do read and remove operations.

Limitations:

1) By using iterator we can always move only towards the forward direction and can't move towards the back direction, these are single direction cursors but not bi-directional cursors.
2) By using iterator we can perform only read and remove operations and we can't perform replacement and addition of new objects.

Java iterator
Iterator
3) To overcome above limitation we should go for List Iterator.
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.