get enum from int java code example
Example 1: java get enum from string
public enum Hello {
A, B, C
};
val = Hello.valueOf("A") // Case sensitive and cannot have spaces in the string
val.equals(Hello.A) // returns true
Example 2: java enum from int
//If performance is not an issue (code is only called a few times)
//The reason this is expensive is that .values() returns an array,
//which is a copy of the original because the array might be modified.
MyEnum.values()[x]
//If performance is an issue (code is run hundreds of times)
public enum MyEnum {
EnumValue1,
EnumValue2;
public static MyEnum fromInteger(int x) {
switch(x) {
case 0:
return EnumValue1;
case 1:
return EnumValue2;
}
return null;
}
}