How to convert enum value to int?
Solution 1:
You'd need to make the enum expose value
somehow, e.g.
public enum Tax {
NONE(0), SALES(10), IMPORT(5);
private final int value;
private Tax(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
...
public int getTaxValue() {
Tax tax = Tax.NONE; // Or whatever
return tax.getValue();
}
(I've changed the names to be a bit more conventional and readable, btw.)
This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.
Solution 2:
I prefer this:
public enum Color {
White,
Green,
Blue,
Purple,
Orange,
Red
}
then:
//cast enum to int
int color = Color.Blue.ordinal();
Solution 3:
If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.
If you want a unique number that represent the enum value, you can use ordinal()
.
Solution 4:
Sometime some C# approach makes the life easier in Java world..:
class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;