Home‎ > ‎Applied Core Java‎ > ‎Collection Framework‎ > ‎

Enumeration

Problem : Create a program that fetch elements from a collection sequentially.

Program :

Step 1 - Coding

Create a text file c:\sunilos\Test.java  and copy below contents.

import java.util.Enumeration;

import java.util.Vector;

/*
 * A program to implement Enumeration .
 */

public class TestEnumeration {

    public static void main(String[] args) {
        Vector v = new Vector();

        v.add("Jay");
        v.add("Viru");
        v.add("Basanti");

        // Get all elements and print with help of Enumeration interface
        Enumeration e = v.elements(); // Get java.util.Enumeration objects

        System.out.println("Print All Elements with help of Enumeration ");

        while (e.hasMoreElements()) { // Checks if any element in list
            // Get next available element
            System.out.println(e.nextElement());
        }

    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestEnumeration.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestEnumeration.java with help of 
    • javac TestEnumeration.java command. Compiled class file will be created in the same folder
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestEnumeration command.

Output

C:\sunilos>java TestEnumeration
Print All Elements with help of Enumeration
Jay
Viru
Basanti


FAQ

What is Enumeration?

  1. An object that implements the Enumeration interface generates a series of elements, one at a time.
  2. Successive calls to the nextElement method return successive elements of the series.

Most Interesting methods?

  • hasMoreElements() - Tests if this enumeration contains more elements.
  • nextElement() - Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

<<Previous | Next>>
ċ
Prachi Pacharne,
Oct 16, 2015, 6:49 AM
Comments