A 'for' loop to iterate over an enum in Java
I have an enum
in Java for the cardinal & intermediate directions:
public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
How can I write a for
loop that iterates through each of these enum
values?
.values()
You can call the values()
method on your enum.
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.
枚举值#():
for (Direction d : Direction.values()) {
System.out.println(d);
}
你可以这样做,如下所示:
for (Direction direction : EnumSet.allOf(Direction.class)) {
// do stuff
}
链接地址: http://www.djcxy.com/p/2672.html
下一篇: 'for'循环遍历Java中的枚举