本文翻译自:A 'for' loop to iterate over an enum in Java
I have an enum
in Java for the cardinal & intermediate directions: 我有一个Java的enum
主要和中间方向:
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? 如何编写迭代这些enum
值的for
循环?
#1楼
参考:https://stackoom.com/question/4dSB/一个-for-循环迭代Java中的枚举
#2楼
Enum#values(): 枚举值#():
for (Direction d : Direction.values()) {
System.out.println(d);
}
#3楼
.values()
You can call the values()
method on your enum. 您可以在枚举上调用values()
方法。
for (Direction dir : Direction.values()) {
// do what you want
}
This values()
method is implicitly declared by the compiler . 这个values()
方法由编译器隐式声明 。 So it is not listed on Enum
doc. 所以它没有在Enum
doc上列出。
#4楼
You can do this as follows: 你可以这样做:
for (Direction direction : EnumSet.allOf(Direction.class)) {
// do stuff
}
#5楼
If you don't care about the order this should work: 如果您不关心订单,这应该有效:
Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
// do stuff
}
#6楼
for(Direction dir : Direction.values())
{
}