Java Mapping for Enumerations

A Slice enumeration maps to the corresponding enumeration in Java. For example:

Slice
enum Fruit { Apple, Pear, Orange }

The Java mapping for Fruit is shown below:

Java
public enum Fruit implements java.io.Serializable
{
    Apple,
    Pear,
    Orange;

    public int value();

    public static Fruit valueOf(int v);

    // ...
}

Given the above definitions, we can use enumerated values as follows:

Java
Fruit f1 = Fruit.Apple;
Fruit f2 = Fruit.Orange;

if(f1 == Fruit.Apple) // Compare with constant
{
    // ...
}

if(f1 == f2)          // Compare two enums
{
    // ...
}

switch(f2)            // Switch on enum
{
    case Fruit.Apple:
        // ...
        break;
    case Fruit.Pear:
        // ...
        break;
    case Fruit.Orange:
        // ...
        break;
}

The Java mapping includes two methods of interest. The value method returns the Slice value of an enumerator, which is not necessarily the same as its ordinal value. The valueOf method translates a Slice value into its corresponding enumerator, or returns null if no match is found. Note that the generated class contains a number of other members, which we have not shown. These members are internal to the Ice run time and you must not use them in your application code (because they may change from release to release).

In the Fruit definition above, the Slice value of each enumerator matches its ordinal value. This will not be true if we modify the definition to include a custom enumerator value:

Slice
enum Fruit { Apple, Pear = 3, Orange }

The table below shows the new relationship between ordinal value and Slice value:

EnumeratorOrdinalSlice
Apple00
Pear13
Orange24

Java enumerated types inherit implicitly from java.lang.Enum, which defines methods such as ordinal and compareTo that operate on the ordinal value of an enumerator, not its Slice value.

See Also