📜  来自 int 的 java 枚举 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:20.303000             🧑  作者: Mango

代码示例1
//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;
    }
}