2012-08-10 137 views

回答

14

Enum每个类型具有一个静态values方法,该方法返回一个包含它们被声明的顺序所有枚举类型的值的数组。

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

Java 7的规格说明文件链接: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.2

+3

+1如果Java 5.0是EOL,我建议使用Java 7引用。 – 2012-08-10 09:36:51

+0

@PeterLawrey完成。 – 2012-08-10 10:02:22

+2

对于下来的选民,如果你可以留下一个改善答案的建议,我会很乐意这样做。 – 2012-08-10 10:06:38

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(); 
1

正如前2回答说,这个命令就是声明的顺序。但是,依赖这个命令(或枚举的序号)并不是一个好习惯。如果有人重新排列声明或在声明的中间添加一个新元素,代码的行为可能会意外改变。 如果有一个固定的订单,我会执行Comparable

1

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

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

values()static method of Enum,其中始终以相同的顺序返回值。