How do I create a java.util.Hashtable and iterates its contents?

The code snippet shows you how to create and instance of Hashtable that stores Integer values using a String keys. After that we iterate the elements of the Hashtable using the Enumeration interface.

package org.kodejava.util;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    public static void main(String[] args) {
        // Creates an instance of Hashtable
        Hashtable<String, Integer> numbers = new Hashtable<>();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);

        // Returns an enumeration of the keys in this Hashtable
        Enumeration<String> keys = numbers.keys();
        while (keys.hasMoreElements()) {
            // Returns the next element of this enumeration if this
            // enumeration object has at least one more element to
            // provide
            String key = keys.nextElement();
            System.out.printf("Key: %s, Value: %d%n", key, numbers.get(key));
        }
    }
}

How do I read java.util.Vector object using java.util.Enumeration?

The following code snippets show you how to iterate and read java.util.Vector elements using the java.util.Enumeration.

package org.kodejava.util;

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

public class VectorEnumeration {

    public static void main(String[] args) {
        Vector<String> data = new Vector<>();
        data.add("one");
        data.add("two");
        data.add("three");

        StringBuilder sb = new StringBuilder("Data: ");

        // Iterates vector object to read it elements
        for (Enumeration<String> enumeration = data.elements();
             enumeration.hasMoreElements(); ) {
            sb.append(enumeration.nextElement()).append(",");
        }

        // Delete the last ","
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb);
    }
}

How do I sort an java.util.Enumeration?

In this code snippet you will see how to sort the content of an Enumeration object. We start by creating a random numbers and stored it in a Vector. We use these numbers and create a Enumeration object by calling Vector‘s elements() method. We convert it to java.util.List and then sort the content of the List using Collections.sort() method. Here is the complete code snippet.

package org.kodejava.util;

import java.util.*;

public class EnumerationSort {
    public static void main(String[] args) {
        // Creates random data for sorting source. Will use java.util.Vector
        // to store the random integer generated.
        Random random = new Random();
        Vector<Integer> data = new Vector<>();
        for (int i = 0; i < 10; i++) {
            data.add(Math.abs(random.nextInt()));
        }

        // Get the enumeration from the vector object and convert it into
        // a java.util.List. Finally, we sort the list using
        // Collections.sort() method.
        Enumeration<Integer> enumeration = data.elements();
        List<Integer> list = Collections.list(enumeration);
        Collections.sort(list);

        // Prints out all generated number after sorted.
        for (Integer number : list) {
            System.out.println("Number = " + number);
        }
    }
}

An example result of the code above is:

Number = 20742427
Number = 163885840
Number = 204704456
Number = 560032429
Number = 601762809
Number = 1300593322
Number = 1371678147
Number = 1786580321
Number = 1786731301
Number = 1856215303

How do I get name of enum constant?

This example demonstrate how to user enum‘s name() method to get enum constant name exactly as declared in the enum declaration.

package org.kodejava.basic;

enum ProcessStatus {
    IDLE, RUNNING, FAILED, DONE;

    @Override
    public String toString() {
        return "Process Status: " + this.name();
    }
}

public class EnumNameDemo {
    public static void main(String[] args) {
        for (ProcessStatus processStatus : ProcessStatus.values()) {
            // Gets the name of this enum constant, exactly as
            // declared in its enum declaration.
            System.out.println(processStatus.name());

            // Here we call to our implementation of the toString
            // method to get a more friendly message of the
            // enum constant name.
            System.out.println(processStatus);
        }
    }
}

Our program result:

IDLE
Process Status: IDLE
RUNNING
Process Status: RUNNING
FAILED
Process Status: FAILED
DONE
Process Status: DONE

How do I get ordinal value of enum constant?

This example demonstrate the use of enum ordinal() method to get the ordinal value of an enum constant.

package org.kodejava.basic;

enum Color {
    RED, GREEN, BLUE
}

public class EnumOrdinal {
    public static void main(String[] args) {
        // Gets the ordinal of this enumeration constant (its
        // position in its enum declaration, where the initial 
        // constant is assigned an ordinal of zero)
        System.out.println("Color.RED  : " + Color.RED.ordinal());
        System.out.println("Color.GREEN: " + Color.GREEN.ordinal());
        System.out.println("Color.BLUE : " + Color.BLUE.ordinal());
    }
}

The program print the following result:

Color.RED  : 0
Color.GREEN: 1
Color.BLUE : 2

How do I define a field in enum type?

As we know that Java enumeration type is powerful compared to enum implementation in other programming language. Basically enum is class typed, so it can have constructors, methods and fields.

In the example below you’ll see how a field is defined in an enumeration type. Because each constant value for the Fruit enum is a type of Fruit itself it will have its own price field. The price field holds a unique value for each constant such as APPLE, ORANGE, etc.

In the result you’ll see that the constructor will be called for each constant value and initialize it with the value passed to the constructor.

package org.kodejava.basic;

enum Fruit {
    APPLE(1.5f), ORANGE(2), MANGO(3.5f), GRAPE(5);

    private final float price;

    Fruit(float price) {
        System.out.println("Name: " + this.name() + " initialized.");
        this.price = price;
    }

    public float getPrice() {
        return this.price;
    }
}

public class EnumFieldDemo {
    public static void main(String[] args) {
        // Get the name and price of all enum constant value.
        for (Fruit fruit : Fruit.values()) {
            System.out.printf("Fruit = %s; Price = %5.2f%n",
                    fruit.name(), fruit.getPrice());
        }
    }
}

Our demo result is below:

Name: APPLE initialized.
Name: ORANGE initialized.
Name: MANGO initialized.
Name: GRAPE initialized.
Fruit = APPLE; Price =  1.50
Fruit = ORANGE; Price =  2.00
Fruit = MANGO; Price =  3.50
Fruit = GRAPE; Price =  5.00

How do I get enum constant value corresponds to a string?

The valueOf() method of an enum type allows you to get an enum constant that the value corresponds to the specified string. Exception will be thrown when we pass a string that not available in the enum.

package org.kodejava.basic;

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
package org.kodejava.basic;

public class EnumValueOfTest {
    public static void main(String[] args) {
        // Using valueOf() method we can get an enum constant whose
        // value corresponds to the string passed as the parameter.
        Day day = Day.valueOf("SATURDAY");
        System.out.println("Day = " + day);
        day = Day.valueOf("WEDNESDAY");
        System.out.println("Day = " + day);

        try {
            // The following line will produce an exception because the
            // enum type does not contain a constant named JANUARY.
            day = Day.valueOf("JANUARY");
            System.out.println("Day = " + day);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above:

Day = SATURDAY
Day = WEDNESDAY
java.lang.IllegalArgumentException: No enum constant org.kodejava.basic.Day.JANUARY
    at java.base/java.lang.Enum.valueOf(Enum.java:273)
    at org.kodejava.basic.Day.valueOf(Day.java:3)
    at org.kodejava.basic.EnumValueOfTest.main(EnumValueOfTest.java:15)

How do I get constants name of an enum?

To get the constants name of an enumeration you can use the values() method of the enumeration type. This method return an array that contains a list of enumeration constants.

package org.kodejava.basic;

public enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
}
package org.kodejava.basic;

public class EnumValuesTest {
    public static void main(String[] args) {
        // values() method return an array that contains a list of the
        // enumeration constants.
        Month[] months = Month.values();
        System.out.println("Month size: " + months.length);

        // We can use for each statement to print each enumeration
        // constant.
        for (Month month : Month.values()) {
            System.out.println("Month: " + month);
        }
    }
}

How do I create enumerations type?

Enumeration is a list of named constants. Every most commonly used programming languages support this feature. But in Java it is officially supported since version 5.0. In Java programming language an enumeration defines a class type. Because an enumeration is a class it can have a constructors, methods, and instance variables.

To create an enumeration we use the enum keyword. For example below is a simple enumeration that hold a list of notebook producers:

package org.kodejava.basic;

public enum Producer {
    ACER, APPLE, DELL, FUJITSU, LENOVO, TOSHIBA
}

Below we use our enumeration in a simple program.

package org.kodejava.basic;

public class EnumDeclaration {
    public static void main(String[] args) {
        // Creates an enum variable declaration and assign the value to
        // Producer.APPLE.
        Producer producer = Producer.APPLE;

        if (producer == Producer.LENOVO) {
            System.out.println("Produced by Lenovo.");
        } else {
            System.out.println("Produced by others.");
        }
    }
}

The ACER, APPLE, DELL identifiers are called enumeration constants. Every named constants have an implicitly assigned public and static access modifiers. Although the enumeration is a class type, to create an enumeration variable we don’t use the new keyword. We create an enum just like creating a primitive type of data, as you can see in the example above.