enum.values()的顺序总是一样的

M.J*_*.J. 21 java enums

可能重复:
enum.values() - 是返回的枚举确定性的顺序

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

enum Direction {

    EAST,
    WEST,
    NORTH,
    SOUTH
}
Run Code Online (Sandbox Code Playgroud)

如果我values()在Direction enum上说,那么值的顺序将始终保持相同.我的意思是值的顺序总是在下面的foramt中:

EAST,WEST,NORTH,SOUTH
Run Code Online (Sandbox Code Playgroud)

或者订单可以在任何时间点改变.

Aja*_*rge 26

每种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是EOL. (3认同)
  • 对于选民来说,如果你能提出改善答案的建议,我会很乐意这样做. (2认同)

ass*_*ias 5

该方法的行为在Java语言规范#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();
Run Code Online (Sandbox Code Playgroud)