关于 java:enum.values() 的顺序是否总是相同的 | 珊瑚贝

will the order for enum.values() always same

本问题已经有最佳答案,请猛点这里访问。


Possible Duplicate:
enum.values() – is an order of returned enums deterministic

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

1
2
3
4
5
6
7
enum Direction {

    EAST,
    WEST,
    NORTH,
    SOUTH
}

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

1
EAST,WEST,NORTH,SOUTH

或者订单可以随时更改。


每个 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 已停产。
  • 对于否决的选民,如果您可以提出改进答案的建议,我很乐意这样做。


该方法的行为在 Java 语言规范 #8.9.2 中定义:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 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();

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

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

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


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


来源:https://www.codenong.com/11898900/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_10149.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?