What is the difference between Enumeration interface and enum in Java?


Enum in Java is a datatype which stores a set of constant values. You can use these to store fixed values such as days in a week, months in a year etc.

You can define an enum using the keyword enum followed by the name of the enumeration as −

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Just like arrays, the elements/constants in an enum are identified using numbers starting from 0 in the above example the days are identified using numbers as shown in the following illustration −

Retrieving values from an enum

You can retrieve all the elements of an enum using the values() method.

Example

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumerationExample {
   public static void main(String args[]) {
      Days constants[] = Days.values();
      System.out.println("Value of constants: ");
      for(Days d: constants) {
         System.out.println(d);
      }
   }
}

Output

Value of constants:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Enumeration Interface

In java.util package Java provides an interface with name Enumeration, an object implementing this interface generates a series of elements and you can retrieve elements from this using the nextElement() method.

Collections like Vector, HashTable etc. has a method named elements() which returns an Enumeration (interface) object containing all the elements in the collection. Using this object, you can get the elements one by one using the nextElement() method.

If you invoke this method on an empty collection or, after reaching the end of the collection a NosuchElementException will be generated at the run time.

Example

import java.util.Enumeration;
import java.util.Vector;
public class EnumerationExample {
   public static void main(String args[]) {
      //instantiating a Vector
      Vector<Integer> vec = new Vector<Integer>( );
      //Populating the vector
      vec.add(1254);
      vec.add(4587);
      vec.add(5211);
      vec.add(4205);
      vec.add(1124);
      vec.add(8115);
      //Retrieving the elements using the Enumeration
      Enumeration<Integer> en = vec.elements();
      while(en.hasMoreElements()) {
         System.out.println(en.nextElement());
      }
   }
}

Output

1254
4587
5211
4205
1124
8115

Updated on: 07-Aug-2019

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements