I need to create an enumeration with approximately 300 values and be able to get its value by id (int). I currently have this:
public enum Country {
DE(1), US(2), UK(3);
private int id;
private static Map<Integer, Country> idToCountry = new HashMap<>();
static {
for (Country c : Country.values()) {
idToCountry.put(c.id, c);
}
}
Country(int id) {
this.id = id;
}
public static Country getById(int id) {
return idToCountry.get(id);
}
}
This listing will be used a lot, so I wonder how much this is the best performance solution.
I read http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html again and again, but could not find the part that describes what time it is
static {
}
Block is calledand if it is guaranteed that it will be called only once. So is that?
source
share