如何获得枚举的数值?

时间:2012-07-18 20:50:27

标签: java enums

假设你有

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

如何得到代表该星期日的int为0,星期三为3等?

4 个答案:

答案 0 :(得分:87)

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); 
     }
}

答案 1 :(得分:8)

您可以致电:

MONDAY.ordinal()

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

答案 2 :(得分:2)

Take a look at the API它通常是一个体面的起点。虽然我没有猜到没有遇到过这种情况,但你打电话给ENUM_NAME.ordinal()

答案 3 :(得分: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());
  }

}

<强> API:

/**
     * 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;
    }