Java Enumeration | Iterators in Java

Java Enumeration | In the previous tutorial, we knew that ArrayList in Java is a resizable array that stores elements in the memory dynamically.

If the capacity of the array is exceeded then a new array with a larger capacity will be created and all the existing elements from the current array will be copied into the new array.

Now in this tutorial, we will learn what is iterators in java, and their types.

Iterators in Java


Iterators in Java are used to retrieve the elements one by one from a collection object. They are also called cursors in java. Let’s understand this concept with a realtime 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 from the collection object. Therefore, we need to learn iterators or cursors concepts in Java.

Types of Iterators in Java


There are four types of iterators or cursors available in Java. They are as follows:
  • Enumeration
  • Iterator
  • ListIterator
  • Spilterator
Java Iterators: Enumeration in Java

Each Java iterator has some advantages and limitations. In this tutorial, we will discuss some basic points about Enumeration. We will discuss Iterator, ListIterator, and Spliterator in the coming tutorials one by one.

Enumeration in Java


Enumeration is the first iterator that was 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 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. 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 an object of enumeration by calling elements() method of the Vector class. The syntax for creating an object of enumeration in java is as follows:

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 the 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 an enumeration object, internally, we are creating an 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:

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 the Iterator interface.

Vector$ListItr ➨ ListItr is the inner class inside the vector which implements the 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 some example programs based on concepts of these methods to understand better.

Program source code 2:

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 < = 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 elements one by one. So, we will require Enumeration concept. 

// Create object of Enumeration by calling 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

Now let’s perform the same program using the generic concept.

Program source code 3:

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<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


There are many limitations of using enumeration interface in java. They are as follows:

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.
4. Java is not recommended to use it in new projects.

To overcome these limitations, We should go for the next level Iterator concept in Java.

Hope that this tutorial has covered almost all important points related to Iterators in Java and java enumeration interface. I hope that you will have understood this topic and enjoyed it.

In the next tutorial, we will learn the second way: Iterator in Java.
Thanks for reading!!!Next ⇒  Iterator in Java⇐ PrevNext ⇒

Leave a Comment