For example, I have two elements in an enum. I would like the first to be represented by the integer value 0 and the string A, but the second to be represented by the integer value of 2 and the string "B" (as opposed to 1). Is this possible?
Currently, my enum is declared as this:
public enum Constants {
ZERO("Zero");
TWO("Two");
}
If I were to get the integer values of ZERO and TWO, I would currently get 0 and 1, respectively. However, I would like to get 0 and 2.
Define an appropriately named integer field for your enum and initialize it to whatever value suits you best. The internal ordinal of enums is not meant to carry an meaning.
I assume you are referring to a way to make the ordinal of the Enum return a user-defined value. If this is the case, no.
If you want to return a specific value, implement (e.g. getValue()) and pass it in the Enum constructor.
For example:
public enum Constants {
ZERO("Zero",0),
TWO("Two",2);
final private String label;
final private int value;
Constants(String label, int value) {
this.label = label;
this.value= value;
}
public int getValue() {
return value;
}
public String getLabel() {
return label;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With