天天看點

Java周遊枚舉類型(iterate enum in java)

假設有枚舉類型

public enum Direction {

NORTH,

NORTHEAST,

EAST,

SOUTHEAST,

SOUTH,

SOUTHWEST,

WEST,

NORTHWEST

}

如何周遊擷取所有的值?

解決方案,利用java編譯器隐式聲明的.values()方法

for (Direction dir : Direction.values()) {

// do what you want

}

This values() method is implicitly declared by the compiler. So it is not listed on Enum doc.

It is an implicit method that exists only in the compiler. Therefore the base class can not declare a method with the same name and thus it does not get included in the automatically generated Javadocs

參考連結:

[url]http://stackoverflow.com/questions/1104975/for-loop-to-iterate-over-enum-in-java[/url]