Iterator Interface in Java
Most of the time Java developer used this interface to iterate the elements from a collections class.It is a natural iterator as we can apply it to any Collection object. By using Iterator interface, we can perform both read and remove operations, We can remove any element and read also. It is updated version of Enumeration with the additional functionality of remove-ability of an element.
Iterator must be used whenever we want to iterate elements in all Collection framework interfaces like Set, List, Queue, Deque, and Map in all implemented classes. An iterator is the only cursor available for entire collection framework.
In Java, Iterator object can be created by calling iterator() method available in Collection interface. Iterator interface has three methods.
// Here "c" is any Collection object. itr is of type Iterator interface and refers to a collection object.
Iterator itr = c.iterator();
// Returns true if the iteration has more elements
public boolean hasNext();
// Returns the next element in the iteration
// It throws NoSuchElementException if no more element present
public Object next();
// Remove the next element in the iteration
// This method can be called only once per call to next()
public void remove();
remove() method can throw two exceptions
UnsupportedOperationException : If the remove operation is not supported by this iterator
IllegalStateException : If the next method has not yet been called, or the remove method has already been called after the last call to the next method
// Java program to demonstrate Iterator
class TestIterator { public static void main(String[] args) { ArrayList al = new ArrayList(); for (int i = 0; i < 10; i++) { al.add(i); System.out.println(al); } // at beginning itr(cursor) will point to index just before the first // element in al Iterator itr = al.iterator(); // checking the next element availabilty while (itr.hasNext()) { // moving cursor to next element int i = (Integer) itr.next(); // getting even elements one by one System.out.print(i + " "); // Removing odd elements if (i % 2 != 0) { itr.remove(); } System.out.println(); System.out.println(al); } } }
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0 1 2 3 4 5 6 7 8 9 [0, 2, 4, 6, 8]
Limitations of Iterator :
By the Iterator Interface, only forward direction iterating is possible.
Replacement and addition of new elements are not supported by Iterator.
post a comment