Java Iterator Interface Example

Java Iterator Interface Example

Java Iterator Interface Example: JDK 1.0 Enumeration is replaced by Iterator interface in JDK 1.2. Being latest, it comes with many advantages over Enumeration. Like Enumeration, Java Iterator interface is also used for iterating the elements.
Java Iterator Interface Example

Java Iterator Interface Example

The above program just looks like Enumeration only, but replaced by Iterator. The methods are hasNext() in place of hasMoreElements(). And also next() in place of nextElement(). These two new methods, designers felt more appropriate to remember easily.

Java Iterator over Java Enumeration

Let us see where Iterator takes a lead over Enumeration. With Iterator, we can remove an element from the vector. Removing with Iterator, removes in the original Vector itself. This facility does not exist with Enumeration. Enumeration is useful to just print the elements.

Java Iterator interface comes with the following methods.

1. public abstract boolean hasNext();
2. public abstract Object next();
3. public abstract void remove();

Let us rewrite the above code where elements Raju and Rao are removed. After removing, the vector elements are again read and printed to check whether removal is really affected or not. Following Java Iterator Interface Example uses the above methods.

Java Iterator Interface Example

The remove method of Iterator removes Raju and Rao. It is proved when the elements are printed again with it3.

The Iterator comes with a sub interface "ListIterator". ListIterator comes with some more advantages over Iterator.

8 thoughts on “Java Iterator Interface Example

  1. Ashish Dwivedi

    Sir,
    I am trying this code .
    Vector vb = new Vector();
    vb.add(123);
    vb.add(342);
    Iterator it = vb.iterator();
    vb.add(32);
    while (it.hasNext()) {
    System.out.println(it.next());
    }

    it gives
    “java.util.ConcurrentModificationException”

  2. madhusudhan

    Vector vect1 = new Vector();
    vect1.addElement(“Reddy”);
    vect1.addElement(“Ratnakar”);
    Iterator it1 = vect1.iterator();

    how Vector object(vect1) can assign to Iterator object(It1), they both are different classes

    1. S. Nageswara Rao, Corporate Trainer Post author

      Refer the class signature of Vector. class Vector implements List interface. List interface extends Collection interface. iterator) is a method of Collection interface. For this reason, Vector can make use of the methods of Collection and List interfaces.

Leave a Reply

Your email address will not be published. Required fields are marked *