Answers for "get enum from int java"

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
Posted by: Guest on May-18-2021
0

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;
    }
}
Posted by: Guest on January-05-2021

Browse Popular Code Answers by Language