HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

A for-loop to iterate over an enum in Java

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
enumjavaoverforiterateloop

Problem

I have an enum in Java for the cardinal and 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?

Solution

.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.

Code Snippets

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

Context

Stack Overflow Q#1104975, score: 1500

Revisions (0)

No revisions yet.