Documentation inline with the code.
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Intesar Mohammed
*
* Reverse Enum Lookup example using Map and EnumSet
*/
public enum Status {
WAITING(0),
READY(1),
SKIPPED(-1),
COMPLETED(5);
/**
* code or your required variable can be of any type
*/ private int code;
private Status(int code) {
this.code = code;
}
private static final Map<Integer, Status> lookup =
new HashMap<Integer, Status>();
/**
* Stores all Enum's into lookup
*/
static {
for (Status s : EnumSet.allOf(Status.class)) {
lookup.put(s.code, s);
}
}
/**
*
* toString() is the only api to print Enum value
* All Enum classes can consistently override toString() and provide a simple api
* across different Enums
*
* @return
*/
@Override
public String toString() {
return String.valueOf(code);
}
/**
* Sample lookup code
*
* Status status = Status.get(0);
* Status status = Status.get(5);
* Status status = Status.get(10); // this will return null
*
* Also you can rename get() to reverseLookup() or lookup()
* for readability convenience
*
* @param code
* @return
*/
public static Status get(int code) {
return lookup.get(code);
}
}
reference
Comments
It seems like unnecessary overhead, but I prefer to wrap such maps with Collections.unmodifiableMap(). It makes the intent clear.
Do you know the class EnumMap?
It's a map optimized for Enums and it's very suitable for what you're trying to do.
Regards.
also checkout jdk1.6 documentation
http://download.oracle.com/javase/6/docs/api/java/util/EnumMap.html
Javin
How Garbage collection works in Java
Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.
By the way I have also blogged my experience as 10 examples of enum in java , let me know how do you find it.