Using kind of range in Java Enum

Peanutbutter :

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?

rgettman :

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101184&siteId=1