Friday, 5 January 2018

Universal Iterator in Java


This Iterator can be applied to any collection object. Thus, it is known as Universal Iterator. Universal Iterator can perform both read and remove operations It is an improved version of the Enumeration Iterator with the added functionality of the remove operations.

Universal Iterator must be used to enumerate the elements of the all collection framework implemented interfaces such as Linked Lists, Queue, Stack, Dequeue as well as in implemented class of Map interface. Universal Iterator is the only cursor available for the entire collection framework.

Iterator itr = c.iterator();

Here, c refers to the collection object.

Iterator Interface has three defined methods:

1. public boolean hasNext(): This method returns true if there are more elements in the collection object and it will throw NoSuchElementException if there is no more element present.

2. public Object next(): It will return the next element of the collection object.

3. public void remove(): It will remove the next element of the object, It can be called only once per call to the next() method. It will throw IllegalStateException if the next() method has not been called yet or if remove() is already called to last next() method. It will also throw the UnsupportedOperationException if the remove method is not supported by the collection object.

Limitations of the Universal Iterator:
1. Only forward iteration is possible.
2. Replacement and addition of new element is not supported.


import java.util.*;

public class UniversalIterator{

    public static void main(String args[]){

           Scanner in=new Scanner(;

              List<Integer> list=new ArrayList<Integer>();

              for(int i=0;i<10;i++){

              Iterator it=list.iterator();


                    int element=(Integer);


              System.out.print("\n\nAfter performing removing operation:\n");


                    int element=(Integer);