Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A 'for' loop to iterate over an enum in Java

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?

like image 725
Nick Meyer Avatar asked Jul 09 '09 16:07

Nick Meyer


People also ask

Can you iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

What are enumerations in Java?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum , use the enum keyword (instead of class or interface), and separate the constants with a comma.


1 Answers

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

like image 87
notnoop Avatar answered Oct 05 '22 19:10

notnoop