Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through an enum in Java? [duplicate]

Let's say I have an enum like so:

public enum Numbers {
    ONE("Uno "),
    TWO("Dos "),
    THREE("Tres ");
}

private final String spanishName;

Numbers(String spanishName) {
    this.spanishName = spanishName;
}

public String getSpanishName() {
    return spanishName;
}

Now I have a method that outputs a given variable.

public void output(String value) {
    printStream.print(value);
}

I want to use a for loop to output all the values in the enum. Something along the lines of this:

for(/*each element in the enum*/) {
    //output the corresponding spanish name
}

Ultimate I want the final output to be Uno Dos Tres. How can I do this using enums and a for loop?

like image 665
Charles Avatar asked May 21 '13 16:05

Charles


People also ask

Can you loop through enum Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.

Can enum have duplicates?

CA1069: Enums should not have duplicate values (code analysis) - .

Can we clone enum in Java?

The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.


3 Answers

for (Numbers n : Numbers.values()) {
   System.out.print(n.getSpanishName() + " ");
}
like image 176
ktm5124 Avatar answered Sep 24 '22 09:09

ktm5124


Use this:

for (Numbers d : Numbers .values()) {
     System.out.println(d);
 }
like image 33
Lokesh Avatar answered Sep 26 '22 09:09

Lokesh


for (Numbers num : Numbers.values()) {
  // do what you want
}

looks like duplicate: A 'for' loop to iterate over an enum in Java

like image 43
Dory Zidon Avatar answered Sep 22 '22 09:09

Dory Zidon