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 枚举上说
1 | EAST,WEST,NORTH,SOUTH |
或者订单可以随时更改。
每个
此方法通常与 for-each 循环结合使用,以迭代枚举类型的值。
Java 7 Spec 文档链接:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.2
该方法的行为在 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(); |
这些值是
正如前面2个答案所说,顺序是声明的顺序。但是,依赖此顺序(或枚举的序数)并不是一个好习惯。如果有人对声明重新排序或在声明中间添加新元素,则代码的行为可能会发生意外变化。
如果有固定顺序,我会实现