Enum with negative/gap value in Java -


i have problem enum in java. have enum starts -1:

    public enum aiptype {         unknown(-1),         none(0),         aipmod(1),         aipnomod(2);          private final int id;         aiptype(int id) {this.id = id;}         public int getvalue() {return id;}     } 

the problem when use code initialize var of aiptype

aiptype @ = aiptype.getvalues()[index]; 

where index number in interval [-1,0,1,2] -1 mess value. i.e. 0 returns unknown, 1 returns aipmod , 2 returns aipnomod.

i used implementation because need set manually numeric value each enum case. in other case have gap beetwen values have same problem: cannot use values() , access [ ].

i tried initialize in way

aiptype @ = aiptype(index); 

but doesn't work.

ideas ? thanks...

we don't know getvalues() method you're using doing. supposed values().

anyway, can add static method in enum, returns correct enum instance value, , invoke wherever need it:

public enum aiptype {     unknown(-1),     none(0),     aipmod(1),     aipnomod(2);      private final int id;     aiptype(int id) {this.id = id;}     public int getvalue() {return id;}      public static aiptype fromvalue(int id) {         (aiptype aip: values()) {             if (aip.getvalue() == id) {                 return aip;             }         }         return null;     } } 

if you're invoking fromvalue() often, might want cache array returned values() inside enum itself, , use it. or better, map better idea.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -