Getting enum associated with int value
You could also include a static method in the enum that iterates through all members and returns the correct one.
public enum LegNo {
NO_LEG(-1),
LEG_ONE(1),
LEG_TWO(2);
private int legIndex;
private LegNo(int legIndex) { this.legIndex = legIndex; }
public static LegNo getLeg(int legIndex) {
for (LegNo l : LegNo.values()) {
if (l.legIndex == legIndex) return l;
}
throw new IllegalArgumentException("Leg not found. Amputated?");
}
}
Now, if you want to get an Enum value by the integer, you just use:
int myLegIndex = 1; //expected : LEG_ONE
LegNo myLeg = LegNo.getLeg(myLegIndex);
EDIT August 2018
Today I would implement this as follows
public enum LegNo {
NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);
private final int value;
LegNo(int value) {
this.value = value;
}
public static Optional<LegNo> valueOf(int value) {
return Arrays.stream(values())
.filter(legNo -> legNo.value == value)
.findFirst();
}
}
You'll have to maintain a mapping inside the enum.
public enum LegNo {
NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);
private int legNo;
private static Map<Integer, LegNo> map = new HashMap<Integer, LegNo>();
static {
for (LegNo legEnum : LegNo.values()) {
map.put(legEnum.legNo, legEnum);
}
}
private LegNo(final int leg) { legNo = leg; }
public static LegNo valueOf(int legNo) {
return map.get(legNo);
}
}
The static block will be invoked only once, so there is practically no performance issue here.
EDIT: Renamed the method to valueOf
as it is more inline with other Java classes.