一个'for'循环遍历Java中的枚举 [英] A 'for' loop to iterate over an enum in Java

查看:133
本文介绍了一个'for'循环遍历Java中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个枚举中间方向:

  public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}

如何编写 for 循环遍历每个枚举值?

解决方案

.values()



您可以在枚举上调用 values()方法。

  for(Direction dir:Direction.values()){
//做你想要的
}
pre>

这个 values()方法是 枚举 doc。


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'循环遍历Java中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆