【问题标题】:will the order for enum.values() always same [duplicate]enum.values() 的顺序是否始终相同[重复]
【发布时间】:2012-08-10 09:30:38
【问题描述】:

可能重复:
enum.values() - is an order of returned enums deterministic

我有一个类似下面的枚举:-

enum Direction {

    EAST,
    WEST,
    NORTH,
    SOUTH
}

如果我在 Direction 枚举上说 values(),那么值的顺序会一直保持不变。我的意思是值的顺序将始终在以下格式中:

EAST,WEST,NORTH,SOUTH

或者订单可以随时更改。

【问题讨论】:

    标签: java enums


    【解决方案1】:

    每个Enum 类型都有一个静态values 方法,该方法返回一个数组,其中包含枚举类型的所有值,按声明顺序

    此方法通常与 for-each 循环结合使用,以迭代枚举类型的值。

    Java 7 Spec 文档链接: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.2

    【讨论】:

    • +1 如果可以的话,我建议使用 Java 7 参考资料,因为 Java 5.0 已停产。
    • 对于反对的选民,如果您可以提出改进答案的建议,我很乐意这样做。
    【解决方案2】:

    该方法的行为在Java Language Specification #8.9.2中定义:

    此外,如果 E 是枚举类型的名称,则该类型具有以下隐式声明的静态方法:

    /**
    * Returns an array containing the constants of this enum   
    * type, in the order they're declared.  This method may be  
    * used to iterate over the constants as follows:  
    *  
    *    for(E c : E.values())  
    *        System.out.println(c);  
    *  
    * @return an array containing the constants of this enum   
    * type, in the order they're declared  
    */  
    public static E[] values();
    

    【讨论】:

      【解决方案3】:

      正如前面2个答案所说,顺序是声明的顺序。但是,依赖此顺序(或枚举的序数)并不是一个好习惯。如果有人重新排序声明或在声明中间添加新元素,则代码的行为可能会意外更改。 如果有固定顺序,我会执行Comparable

      【讨论】:

        【解决方案4】:

        Enums 用于将变量的值限制为枚举列表中唯一声明的值之一。

        这些值为public static final,即(该特定枚举类型的常量对象),其顺序对于将变量映射到这些对象非常重要。

        values() 是一个static method of Enum,它总是以相同的顺序返回值。

        【讨论】:

          猜你喜欢
          • 2020-01-26
          • 2012-12-19
          • 2016-07-14
          • 2022-01-15
          • 1970-01-01
          • 2015-08-23
          • 1970-01-01
          • 2012-04-09
          • 2011-04-18
          相关资源
          最近更新 更多