34

假设你有

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

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

4

4 回答 4

92
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); 
     }
}
于 2012-07-18T20:52:58.720 回答
8

您可以致电:

MONDAY.ordinal()

但我个人会向 中添加一个属性来enum存储值,在enum构造函数中对其进行初始化并添加一个函数来获取值。这更好,因为如果常量移动,的值MONDAY.ordinal可能会改变。enum

于 2012-07-18T20:54:17.310 回答
2

看看 API,它通常是一个不错的起点。尽管在您调用 ENUM_NAME.ordinal() 之前没有遇到过这个问题,我不会猜到

于 2012-07-18T20:54:58.423 回答
0

是的,只需使用枚举对象的序数方法。

public class Gtry {
  enum TestA {
    A1, A2, A3
  }

  public static void main(String[] args) {
    System.out.println(TestA.A2.ordinal());
    System.out.println(TestA.A1.ordinal());
    System.out.println(TestA.A3.ordinal());
  }

}

接口:

/**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    public final int ordinal() {
        return ordinal;
    }
于 2017-09-28T06:37:29.843 回答