Java Enumeration with example

 

Enumeration is an interface similar to Iterator where the Object implements the Enumeration interface generates a series of elements, one at a time. There are 2 methods like
Java Enumeration with example

  • hasMoreElements() - Checks whether enumeration contains more elements.
  • nextElement() - Returns next element from enumeration if elements present in it. 
Functionality wise its similar to Iterator interface, but by using Iterator we will get additional option like remove operation. Lets see simple example for using Enumeration on Vector Object. 


import java.util.Enumeration;
import java.util.Vector;

public class EnumerationTest {
 
 public static void main(String[] args) {
  
  Vector<String> vec = new Vector<String>();
  vec.add("java");
  vec.add("discover");
  vec.add("Enumeration");
  vec.add("interface");
  
  Enumeration<String> enumer = vec.elements();
  while(enumer.hasMoreElements()){
            System.out.println(enumer.nextElement());
        }
 }
}

OUTPUT:


java
discover
Enumeration
interface

No comments:
Write comments