Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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循环?)

  ask by Nick Meyer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

.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上列出。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...