一尘不染

如何获得枚举的数值?

java

假设你有

public enum Week {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

怎么能int代表星期日是0,星期三是3等?


阅读 565

收藏
2020-12-03

共1个答案

一尘不染

Week week = Week.SUNDAY;

int i = week.ordinal();

但是请注意,如果您更改声明中的枚举常量的顺序,则此值将更改。解决此问题的一种方法是将int值自定义为所有枚举常量,如下所示:

public enum Week 
{
     SUNDAY(0),
     MONDAY(1)

     private static final Map<Integer,Week> lookup 
          = new HashMap<Integer,Week>();

     static {
          for(Week w : EnumSet.allOf(Week.class))
               lookup.put(w.getCode(), w);
     }

     private int code;

     private Week(int code) {
          this.code = code;
     }

     public int getCode() { return code; }

     public static Week get(int code) { 
          return lookup.get(code); 
     }
}
2020-12-03