Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with negative/gap value in Java

Tags:

java

enums

I have a problem with enum in Java. I have an enum that starts from -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 is when I use this code to initialize a var of AipType

AipType at = AipType.getValues()[index];

where index is a number in the interval [-1,0,1,2] the -1 mess up the value. i.e. 0 returns Unknown, 1 returns AipMod and 2 returns AipNoMod.

I used this implementation because I need to set manually the numeric value for each enum case. In other case I have a gap beetwen the values so I have the same problem: I cannot use values() and then access with [ ].

I tried to initialize in this way

AipType at = AipType(index);

but doesn't work.

Ideas ? Thanks...

like image 723
Fry Avatar asked Oct 21 '25 16:10

Fry


1 Answers

We don't know what the getValues() method you're using exactly doing. Is it supposed to be values().

Anyway, you can always add a static method in your enum, which returns the correct enum instance for that value, and invoke it wherever you 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) {
        for (AipType aip: values()) {
            if (aip.getValue() == id) {
                return aip;
            }
        }
        return null;
    }
}

If you're invoking fromValue() too often, you might also want to cache the array returned by values() inside the enum itself, and use it. Or even better, a map would be a better idea.

like image 56
Rohit Jain Avatar answered Oct 23 '25 07:10

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!