我enum在Java中有基本和中间方向的说明:public enum Direction { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST}如何编写一个for循环访问这些enum值的循环?
3 回答

BIG阳
TA贡献1859条经验 获得超6个赞
.values()
您可以values()在枚举上调用该方法。
for (Direction dir : Direction.values()) {
// do what you want
}
该values()方法由编译器隐式声明。因此它未在Enum文档中列出。

慕森卡
TA贡献1806条经验 获得超8个赞
可以通过调用该public static T[] values()类型的隐式方法来获取枚举类型的所有常量:
for (Direction d : Direction.values()) {
System.out.println(d);
}

慕仙森
TA贡献1827条经验 获得超8个赞
您可以按照以下步骤进行操作:
for (Direction direction : EnumSet.allOf(Direction.class)) {
// do stuff
}
添加回答
举报
0/150
提交
取消