Can I specify ordinal for enum in Java?

前端 未结 7 2016
时光说笑
时光说笑 2020-12-01 05:45

The ordinal() method returns the ordinal of an enum instance.
How can I set the ordinal for an enum?

7条回答
  •  失恋的感觉
    2020-12-01 06:41

    The easy answer: just change the order of the constants. The first defined will be 0, the second will be 1, etc. However, this may not be practical if you have constantly changing code, or enums will many many values. You can define a custom method to work around the default ordinal, but MAKE SURE it is well documented to avoid confusion!

    public enum Values
    {
        ONE, TWO, THREE, FOUR;
    
        public int getCustomOrdinal()
        {
            if(this == ONE)
            {
                return 3;
            }
            else if(this == TWO)
            {
                return 0;
            }
            ...
        }
    }
    

提交回复
热议问题