Best way to create enum of strings?
The best way to create an enum
of strings in Java is to define the enum
type with a String
field, and then specify the possible values for the enum
as string literals.
Here is an example of how you can define an enum
of strings in Java:
public enum Color {
RED("red"),
GREEN("green"),
BLUE("blue");
private String value;
private Color(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
In this example, the Color
enum
has three possible values: RED
, GREEN
, and BLUE
. Each value has a corresponding String
field called value
, which holds the string representation of the enum
value.
You can use the enum
values like this:
Color c = Color.RED;
System.out.println(c.getValue()); // Outputs "red"
You can also use the name()
method of the Enum
class to get the string representation of an enum
value:
Color c = Color.RED;
System.out.println(c.name()); // Outputs "RED"
Note that the name()
method returns the enum
value in upper case, while the getValue()
method returns the string representation of the value as specified in the enum
definition.