Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using kind of range in Java Enum

Tags:

java

enums

range

I can define enum values with specific int values but I also want to represent some specific range in a Java enum. What I mean is the following:

public enum SampleEnum {
    A(1),
    B(2),
    C(3),
    D(4),
    //E([5-100]);

    private SampleEnum(int value){
        this.value = value;
    }

    private final int value;
}

Here, for example, is it possible to represent the range between 5 and 100 with a single value(here, it is "E") or is there a better way?

like image 400
Peanutbutter Avatar asked Oct 18 '25 12:10

Peanutbutter


1 Answers

The numbers 5 and 100 are two different values, so storing one value won't work here.

But it's easy enough to define two values in the enum, a low and a high value. For those where the range is just one, set both high and low to the same value.

enum SampleEnum {
    A(1),
    B(2),
    C(3),
    D(4),
    E(5, 100);

    private SampleEnum(int value){
        this.low = value;
        this.high = value;
    }
    private SampleEnum(int low, int high) {
        this.low = low;
        this.high = high;
    }

    private final int low;
    private final int high;
}
like image 106
rgettman Avatar answered Oct 20 '25 03:10

rgettman



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!