JMRboosties JMRboosties - 1 year ago 168
Java Question

Setting an enum by using an int specific to that enum?

Hey all. So I have a set of enums and a db with integers corresponding to those enums. Something like this, for example:

public static enum Day {

public final int fId;

private Day(int id) {
this.fId = id;

I also have a database which only refers to these days by integers, which correspond to their int in the enum set above. What I am looking to do is query a database, which will return an integer, and then set an enumerator to an object based on that integer returned from the db. I could do something like this:

public static Day getDay(int i) {
switch(i) {
case 1:
return Day.SUNDAY;
case 2:
return Day.MONDAY;
//And so on

But for an enum set with over 100 enums inside this doesn't seem very practical.

So is there a way to do this? Again my goal is to simply insert an int value and get back an enumerator without having to create a new method for the many enums in this set. Maybe I should just make this its own class rather than an enumerator, but I was hoping to do it this way. Thanks!

Answer Source

Enums have a built-in ID number, the "ordinal," that you can use for this purpose, as long as you have an easy way to get from the number that represents a given value in the database to the ordinal of the enum. Ordinals are assigned to enum values in the order they are declared in the source file, starting from 0, so in your example, SUNDAY would have an ordinal of 0, MONDAY of 1, etc.

In order to use this, you just have to convert the integer stored in the database to its corresponding ordinal, and then use it to access the enum value. So for your example, an implementation might be

private static Day[] values = Day.values();
public static Day getDay(int i) {
    return values[i - 1];

If the order of the enum values according to their database IDs is the same order with which they are declared in the source code, then you can pretty much just use the above method as-is (except for changing the class name). Otherwise, you may have to do something a little more complicated to map database values to ordinals; perhaps setting up an array, if the mapping is highly nonlinear.

P.S. And of course if you do this, there would be no use for the fId field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download