Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Iterators in Java | Types & Example Program

Iterators in Java


Iterators in Java are used to retrieve the elements one by one in the collection framework. It is also called 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 how will you eat all these 20 apples? one by one or all apples at 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 elements of the collection. So if we want to get these elements one by one, we will require some iterators or cursors to retrieve elements one by one in Java. Therefore, we learn iterators 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 do not include collections framework. Instead, it defined several classes and one interface for storing objects.

When collections came in the Java 1.2 version, several of 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. You can just read 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 an object of enumeration directly. We can create object of enumeration by using elements() method of the Vector class.
Syntax:

public Enumeration elements() // Return type is Enumeration.
For example:
    Enumeration e = v.elements(); // Here, v is a vector class object.

Now you will think that how can create object of Enumeration Interface?

Actually, we cannot create the object of Interface directly or indirectly. When we create an object of interface like this:
    Enumeration e = v.elements();

Internally, elements() method will be executed in the vector class. See below the 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 the 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. They are as follows:

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(): The nextElement() method returns next element in the enumeration. It will throw NoSuchElementException when the enumeration is complete. 


Let’s take an example program based on concepts of these methods to understand better.
Program source code 2:

package iteratorsTest; 
import java.util.Enumeration; 
import java.util.Vector; 
public class EnumerationTest 
{ 
public static void main(String[] args) 
{ 
// Create object of vector class without using generic. 
   Vector v = new Vector(); 
// Add ten elements of integer type using addElement() method. For this we will use for loop. 
   for(int i = 0; i 
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
Now let’s perform the same program using the generic concept.
Program source code 3:
package iteratorsTest; 
import java.util.Enumeration; 
import java.util.Vector; 
public class EnumerationTest 
{ 
public static void main(String[] args) 
{ 
// Create an object of vector class using generic. 
   Vector v = new Vector(); 
 for(int i=0; i
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


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

How to create Iterator object in Java?


Iterator object can be created by calling iterator() method which is present in the Collection interface.

public Iterator iterator() // Return type is Iterator.
For example:
   Iterator itr = c.iterator(); // c is any collection object.
   Iterator itr = c.iterator(); // Generic type.

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 the iteration has more elements in the forward direction. It will give false if all the elements have been iterated.

2. public Object next(): The next() method return next element in the collection. It will throw NoSuchElementException when the iteration is complete.

3. public void remove(): The 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 of type Integer. 
   ArrayList al = new ArrayList(); 
 for(int i = 0; i  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(); // Here, Type casting does not require due to using of generic with Iterator. 
    System.out.println(i); 
// Removing odd elements. 
   if(i % 2! = 0) 
     itr.remove(); 
   } 
  System.out.println(al); 
 } 
}

Look at the below picture to understand the concept of above program.

Output: 
       [0, 1, 2, 3, 4, 5, 6, 7, 8] 
       0 1 2 3 4 5 6 7 8 [0, 2, 4, 6, 8]

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.

Advantage 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 operations.
3. It acts as a Universal cursor for collection API.

Limitation 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 damaged 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. 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 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 child interface of Iterator. Therefore, all the methods of Iterator are available by default to the ListIterator. ListIterator interface has total of 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 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(): This method removes the last element returned by next() or previous() from the list. The return type is ‘nothing’.

8. public void set(Object o): This method replaces the last element returned by next() or previous() with the new element. 

9. public void add(Object o): This method is used to insert a new element in the list.

Let’s take an example program based on 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"); // Adding Grapes after guava. 
    System.out.println(al); 
  } 
  else if(str.equals("Pineapple"))
  { 
    litr.set("Pears"); // Replacing Pineapple element. 
    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 directions.
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 to whole collection API.

Final words
Hope that this tutorial has covered almost all important points related to Iterators in Java with example programs. I hope that you will have understood this topic and enjoyed it.
Thanks for reading!!!
Next ⇒ How to Iterate ArrayList in Java⇐ PrevNext ⇒

The post Iterators in Java | Types & Example Program appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Iterators in Java | Types & Example Program

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×