Scientech Easy Iterators in Java | Types & Example Programs | Scientech Easy

Saturday, October 20, 2018

Iterators in Java | Types & Example Programs

In this tutorial, we will learn Iterators in Java with examples and programs in an easy way and step by step. We will also learn types of Iterators such as Enumeration, Iterator, and ListIterator. This topic is very important and interesting topic in Collection Framework.

Iterators in Java


Iterators in Java are used to retrieve the elements one by one in the collection framework. It is also called the cursors of Java. Let's understand this concept by real-time example.
Suppose that there are 20 apples in a box. If I ask you that how will you eat all these 20 apples? one by one or all apples at a once time. I hope that Your answer will be definitely one by one. That is, you will eat the first apple. After that, you will eat the second apple and so on. Similarly, you assume that box is a collection and apples in the box are the elements of the collection. So if we want to get these elements one by one, we will require some iterators or cursors to retrieve the elements one by one in Java. Therefore, we learn the iterators concepts or cursors concepts in Java.

Types of Iterators in Java


There are three types of iterators or cursors available in Java. They are:
1. Enumeration
2. Iterator
3. ListIterator

Enumeration in Java


➤ Enumeration is the first iterator and introduced in Java 1.0 version. It is located in java.util package. 
➤ It is a legacy interface that is implemented to get elements one by one from the legacy collection classes such as Vector and Properties.
Legacy classes are those classes which are coming from the first version of Java. Early versions of Java does not include the Collections Framework. Instead, it defined several classes and one interface for storing objects. When the collections came in the Java 1.2 version, Several of the original classes were re-engineered to support the collection interfaces. Thus, they are fully compatible with the framework. These old classes are known as legacy classes. The legacy classes defined by java.util are Vector, Hashtable, Properties, Stack, and Dictionary. There is one legacy interface called Enumeration.
➤ Enumeration is read-only i.e you can just read the data from the vector. You cannot remove from the vector using Enumeration.

How to create Enumeration object in Java?


Since enumeration is an interface so we cannot create the object of enumeration directly. We can create the object of enumeration by using elements() method of the Vector class.
  public Enumeration elements() // Return type is Enumeration.
For example
    Enumeration e=v.elements(); // where v is a vector class object. 
Now you will think that how can create the object of Enumeration Interface?
Actually, we cannot create the object of Interface directly or indirectly. When we create the object of interface like this:
    Enumeration e=v.elements();
then internally, elements() method will be executed in the vector class. See below snippet code.
   class Vector {
       elements()
       {
          class  implements Enumeration
        {
           - - - - - - - - - -
          - - - - - - - - - - }
          return (implemented class object);
       } } 
You can see the above code that within elements() method, there is a class that implements enumeration and the implemented class object is gone to return. We can print corresponding internally implemented class name on the console by below snippet code
   Enumeration e=v.elements();
   System.out.println(e.getClass().getName()); // Output: vector$1
vector$1 ➨ Inside vector, $ is the inner class name and 1 is the convention which is applicable for anonymous class. Thus, when we are creating enumeration object, Internally, we are creating enumeration implemented class object. 
Similarly, the same thing happens in the case of Iterator and ListIterator. Let's see code structure.
Program source code 1:
    package iteratorsTest; import java.util.Enumeration; import java.util.Iterator; import java.util.ListIterator; import java.util.Vector; public class InnerClassName { public static void main(String[] args) { Vector v=new Vector(); Enumeration e=v.elements(); Iterator itr=v.iterator(); ListIterator litr=v.listIterator(); System.out.println(e.getClass().getName()); System.out.println(itr.getClass().getName()); System.out.println(litr.getClass().getName()); } }
    Output: java.util.Vector$1 java.util.Vector$Itr java.util.Vector$ListItr
Vector$Itr ➨ Itr is the inner class present inside the vector which implements Iterator interface. 
Vector$ListItr ➨ ListItr is the inner class inside the vector which implements ListIterator interface.

Methods of Enumeration in Java


The Enumeration interface defines the following two methods.
1. public boolean hasMoreElements(): When this method is implemented, hasMoreElements() will return true if there are still more elements to extract and false if all the elements have been enumerated. 
2. public Object nextElement(): nextElement() method returns the next element in the enumeration. It will throw NoSuchElementException when the enumeration is complete. 
Let' see one simple example to understand this concept.
Program source code 2: 
    package iteratorsTest; import java.util.Enumeration; import java.util.Vector; public class EnumerationTest { public static void main(String[] args) { // Create the object of vector class without using generic. Vector v=new Vector(); // Add ten elements with integer type using addElement() method. For this we will use for loop. for(int i=0; i<=10; i++){ v.addElement(i); } System.out.println(v); // It will print all elements at a time like this [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Now we want to get element one by one. So we will require Enumeration concept. // Create the object of Enumeration by calling the elements() method of vector class using object reference variable v. // At the beginning, e (cursor) will point to index just before the first element in v. Enumeration e=v.elements(); // Checking the next element availability using reference variable e and while loop while(e.hasMoreElements()){ // Moving cursor to next element. Object o=e.nextElement(); Integer i=(Integer)o; // Here Type casting is required because the return type of nextElement() method is an object. Therefore, it's compulsory to require type casting. System.out.println(i); } Enumeration en=v.elements(); while(en.hasMoreElements()){ Object o=en.nextElement(); Integer it=(Integer)o; // Getting even elements one by one. if(it%2==0){ System.out.println(it); }} } }
    Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0 1 2 3 4 5 6 7 8 9 10 0 2 4 6 8 10
Program source code 3: Now we will perform the same program using the generic concept.
    package iteratorsTest; import java.util.Enumeration; import java.util.Vector; public class EnumerationTest { public static void main(String[] args) { // Create the object of vector class without using generic. Vector<Integer> v=new Vector<Integer>(); for(int i=0; i<=10; i++){ v.addElement(i); } System.out.println(v); Enumeration e=v.elements(); while(e.hasMoreElements()){ Integer i=(Integer)e.nextElement(); // Direct type casting in one step. System.out.println(i); } Enumeration en=v.elements(); while(en.hasMoreElements()){ Integer it=(Integer)en.nextElement(); if(it%2==0){ System.out.println(it); }} } }
    Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0 1 2 3 4 5 6 7 8 9 10 0 2 4 6 8 10
Limitation of Enumeration
1. Enumeration concept is applicable for only legacy class. Hence, it is not a universal cursor.
2. We can get only read operation by using the enumeration. We cannot perform remove operation.
3. We can iterate using enumeration only in the forward direction.
To overcome these limitations, We should go for the next level Iterator concept.

Iterator in Java


➤ The iterator is introduced in Java 1.2 Collection Framework.
➤ An iterator is a special type of object that provides sequential(one by one) access to the elements of a collection. An Iterator object implements the Iterator interface which is present in java.util package. Therefore, to use an Iterator, you must import either java.util.Iterator or java.util.*.
➤ It is used in Collection Framework to retrieve elements sequentially(one by one).
➤ It is called a Universal Iterator or cursors and can be applied to any collection object.
➤ By using Iterator, we can perform both read and remove operations.

How to create an Iterator object in Java?


Iterator object can be created by calling iterator() method which is present in Collection interface. 
   public Iterator iterator() // Return type is Iterator.
For example
   Iterator itr=c.iterator(); // c is any collection object.
  Iterator<Type> itr=c.iterator(); // Generic.

Methods of Iterator in Java


The Iterator interface provides three methods in Java. They are as follow:
1. public boolean hasNext(): This method will return true if iteration has more elements in the forward direction. It will give false if all the elements have been iterated.
2. public Object next(): next() method return next element in the collection. It will throw NoSuchElementException when the iteration is complete.
3. public void remove(): remove() method removes the last or the most recent retrieved element by the iterator. It must be called after calling next() method otherwise it will throw IllegalStateException. 

Let' see a simple example program on these methods in an easy way and step by step.
Program source code 4: 
    package iteratorsTest; import java.util.ArrayList; import java.util.Iterator; public class IteratorTest { public static void main(String[] args) { // Create the object of ArrayList with type Integer. ArrayList al=new ArrayList(); for(int i=0; i<=8; i++){ al.add(i); } System.out.println(al); // It will print all elements at a time. // Create the object of Iterator by calling iterator() method using reference variable al. // At the beginning, itr(cursor) will point to index just before the first element in al. Iterator itr=al.iterator(); // Checking the next element availability using reference variable itr. while(itr.hasNext()){ // Moving cursor to next element using reference variable itr. Integer i=itr.next(); // Type casting does not require due to use of generic with Iterator. System.out.println(i); // Removing odd elements. if(i%2!=0) itr.remove(); } System.out.println(al); } }
See below picture to understand concept.
Iterators in Java, Java Iterators examples, types of Iterator Enumeration, Iterator, and ListIterator.
Iterators in Java

    Output: [0, 1, 2, 3, 4, 5, 6, 7, 8] 0 1 2 3 4 5 6 7 8 [0, 2, 4, 6, 8]
What is the main difference between Enumeration and iterator with respect to functionality?
➤ By using an enumeration, we can perform only read access but using an iterator, we can perform both read and remove operation.

Advantages of Iterator in Java


Java Iterator has the following advantages. They are: 
1. An iterator can be used with any collection classes.
2. We can perform both read and remove operation.
3. It acts as a Universal cursor for collection API.  

Limitations of Iterator in Java


Java Iterator has the following limitations or drawbacks. They are:
1. By using Enumeration and Iterator, we can move only towards forwarding direction. We cannot move to the backward direction. Hence, these are single direction cursors. 
2. We can perform either read operation or remove operation.
3. We cannot perform the replacement of new objects. For example, suppose there are five mangoes in a box. Out of five, two mangoes are not good but we cannot replace that damage mango with new mango.
To overcome above drawbacks, we should go for ListIterator concept.

ListIterator in Java


ListIterator is the most powerful iterator or cursor and introduced in Java 1.2 version.
It is a bi-directional cursor. That is we can iterate the list in both forward direction and backward direction. 
By using ListIterator, we can perform different kinds of operations such as read, remove, replacement(current object), and the addition of the new objects.

How to create a ListIterator object in Java?


We can create a ListIterator object by using listIterator() method of List interface.
  public ListIterator listIterator()  // return type is ListIterator.
For example
  ListIterator litr=l.listIterator(); // l is any list object.

Methods of ListIterator in Java


Since ListIterator is the child interface of Iterator. Therefore, all the methods of Iterator are available by default to the ListIterator. ListIterator interface has total 9 methods. They are as follows:
Forward direction
1. public boolean hasNext()
2. public Object next()
3. public int nextIndex(): It returns the index of the next element in the list. The return type of this method is an integer.

Backward direction
4. public boolean hasPrevious(): It checks that the list has more elements in the backward direction. If the list has more elements, it will return true. The return type is boolean.
5. public Object previous(): It returns the previous element in the list and moves the cursor position backward direction. The return type is Object.
6. public int previousIndex(): It returns the index of the previous element in the list. The return type is an Integer.

Other capability methods
7. public void remove(): Remove the last element returned by next() or previous() from the list. The return type is 'nothing'.
8. public void set(Object o): It replaces the last element returned by next() or previous() with the new element. 
9. public void add(Object o): Insert a new element in the list.
Let's see a simple example program related to these methods.
Program source code 5:
    package iteratorsTest; import java.util.ArrayList; import java.util.ListIterator; public class ListIteratorTest { public static void main(String[] args) { ArrayList al=new ArrayList(); al.add("Apple"); al.add("Orange"); al.add("Banana"); al.add("Guava"); al.add("Pineapple"); System.out.println(al); // Create the object of ListIterator using listIterator() method. ListIterator litr=al.listIterator(); while(litr.hasNext()){ Object o=litr.next(); String str=(String)o; // Type casting. if(str.equals("Orange")){ litr.remove(); // It will remove orange from the list. System.out.println(al); } else if(str.equals("Guava")){ litr.add("Grapes"); // add Grapes after guava. System.out.println(al); } else if(str.equals("Pineapple")){ litr.set("Pears"); // replace Pineapple. System.out.println(al); } } } }
    Output: [Apple, Orange, Banana, Guava, Pineapple] [Apple, Banana, Guava, Pineapple] [Apple, Banana, Guava, Grapes, Pineapple] [Apple, Banana, Guava, Grapes, Pears]

Advantages of ListIterator in Java


ListIterator has many advantages. They are as follows:
1. It supports many operations such as read, remove, replacement, and the addition of new objects.
2. Using the ListIterator, we can perform Iteration in both forward and backward direction.
3. Methods of ListIterator are easy and simple to use.

Limitations of ListIterator in Java


ListIterator is the most powerful cursor but it still has some limitations. They are as follows:
1. It is applicable only for list implemented class objects. Therefore, it is not a universal Java cursor.
2. It is not applicable for whole collection API.

Final words:
We hope that this article will help you to learn Iterator in Java with examples and programs. This article has covered almost all the topics related to Iterator in Java. You practice all example programs to clear concepts. 

Popular