enum from int code example

Example 1: convert int to enum c#

YourEnum foo = (YourEnum)yourInt;

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;
    }
}

Tags:

Java Example