javadictionaryenumspreon

Preon enum interpretation and mapping


According to http://www.scribd.com/doc/8128172/Preon-Introduction , Preon can be used to decode bits into an enum representation as such:

// Reads a bit from the buffer, and interprets it as an enum value,
// interpreting the number as its ordinal value.
@BoundNumber(size="2")
Type type;

Now, my question is: if you have an enum such as:
public static enum TestEnum {
VALUE_A, VALUE_B
}

Does 00 always map to VALUE_A, and 01 always to VALUE_B because they are written in that (ascending?) order? Can I count on this always being the case? In what ways are enums valued in Java and how does Preon resolve this situation?


Solution

  • Yes they do. The javadoc of the synthetic method values() states it. See JLS 8.9.2.

    Returns an array containing the constants of this enum type, in the order they're declared. This method may be used to iterate over the constants as follows:

    and the javadoc for Enum.ordinal() states

    Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

    So if you do

    TestEnum.values[0]
    

    you will always get

    TestEnum.VALUE_A
    

    in your case.