views:

867

answers:

6

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?

+3  A: 

Enum#values():

 for (Direction d : Direction.values()) {
     System.out.println(d);
 }
dfa
I think you mean "System.out.println(d)".
Nate
+11  A: 

you can do the following:

for (Direction dir : Direction.values()) {
  // do what you want
}
notnoop
+3  A: 

You can do this as follows:

for (Direction direction : EnumSet.allOf(Direction.class)) {
  // do stuff
}
toluju
Provided you import java.util.EnumSet
Nate
+1  A: 

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}
Tom
Provided you import java.util.EnumSet and java.util.Set
Nate
+2  A: 
for(Direction dir : Direction.values())
{

}
+1  A: 
    for (Direction  d : Direction.values()) {
       //your code here   
    }
akf