2012-07-18 129 views
32

假设你有如何获取枚举的数值?

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

一个如何得到int表示周日是0,周三是3等?

回答

85
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

+1提供一个很好的答案,其中有1衬垫就已经足够了 – avalancha 2013-12-02 09:07:22

8

您可以拨打:

MONDAY.ordinal() 

,但我个人的属性添加到enum存储该值,将其初始化为enum构造函数并添加一个函数以获取该值。这样更好,因为如果enum常量被移动,则MONDAY.ordinal的值可能会更改。

2

Take a look at the API它通常是一个体面的地方开始。虽然我不会猜到没有遇到过这个问题之前,你打电话给ENUM_NAME.ordinal()

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; 
    } 
+0

5年晚,不比任何一个以前的答案 – Trilarion 2018-01-03 20:43:28

+0

@Trilarion的,现在你已经5年多了,你有更好的答案吗? ;) – 2018-01-04 04:55:09