Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

The ordinal always maps to the declared order of the enums. However, I would be wary of ever using the ordinal like that. If another developer changes the ordering of the enum declarations, your program will break in very subtle ways. I believe Josh Bloch mentions this in Effective Java.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top