Can I specify ordinal for enum in Java?

前端 未结 7 2012
时光说笑
时光说笑 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:49

    As the accepted answer points out, you can't set the ordinal. The closest you can get to this is with a custom property:

    public enum MonthEnum {
    
        JANUARY(1),
        FEBRUARY(2),
        MARCH(3),
        APRIL(4),
        MAY(5),
        JUNE(6),
        JULY(7),
        AUGUST(8),
        SEPTEMBER(9),
        OCTOBER(10),
        NOVEMBER(11),
        DECEMBER(12);
    
        MonthEnum(int monthOfYear) {
            this.monthOfYear = monthOfYear;
        }
    
        private int monthOfYear;
    
        public int asMonthOfYear() {
            return monthOfYear;
        }
    
    }
    

    Note: By default, enum values start at 0 (not 1) if you don't specify values. Also, the values do not have to increment by 1 for each item.

提交回复
热议问题