Showing posts with label values. Show all posts
Showing posts with label values. Show all posts

Friday, December 9, 2011

Java Enum from value

There are different levels of using Enums in Java. From the simplest one:
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE;
}

to using constructor, values and methods:
public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}

Note that the constructor can only be private or package default, to 'create' an Enum follow below:

To get an Enum from a value (e.g. after storing the value in DB) you can use valueOf() which looks up an Enum based on the given string. Or use values() to look it up directly in the array of possible values, e.g.:Color.values()[2];

Note: valueOf() may throw IllegalArgumentException so, check for that if you don't want a runtime exception.

Edit: From pk's comment and link below I discovered the correct way to use the valueOf() method is to pass the enum name, not the value. E.g. Color.valueOf("WHITE") would give the Color enum WHITE, instead of Color.valueOf("21") which would not. Thanks. :)

Code and thoughts found at: http://javahowto.blogspot.com/2008/04/java-enum-examples.html
http://stackoverflow.com/questions/2418729/whats-the-best-practice-to-look-up-java-enums
http://www.coderanch.com/t/401264/java/java/cast-int-enum