【问题标题】:How to get enum's numeric value?如何获取枚举的数值?
【发布时间】:2012-07-18 20:50:26
【问题描述】:

假设你有

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

如何获得int 表示星期日是 0,星期三是 3 等等?

【问题讨论】:

    标签: java enums


    【解决方案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); 
         }
    }
    

    【讨论】:

    • +1 提供了一个很好的答案,其中 1-liner 就足够了
    【解决方案2】:

    您可以致电:

    MONDAY.ordinal()
    

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

    【讨论】:

      【解决方案3】:

      Take a look at the API 通常是一个不错的起点。虽然在你调用 ENUM_NAME.ordinal() 之前我不会猜到这个问题

      【讨论】:

        【解决方案4】:

        是的,只需使用枚举对象的ordinal方法即可。

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

        【讨论】:

        • 晚了 5 年,并不比以前的任何答案都好
        • @Trilarion,现在你迟到了 5 年以上,你有更好的答案吗? ;)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-05
        • 2015-06-16
        • 2014-02-02
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        相关资源
        最近更新 更多