A 39for39 loop to iterate over an enum in Java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

.values()

You can call the values() method on your enum.

for (Direction dir : Direction.values()) {
  // do what you want
}

http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/1104975/a-for-loop-to-iterate-over-an-enum-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils