Peanutbutter
Peanutbutter

Reputation: 65

Using kind of range in Java Enum

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?

Upvotes: 4

Views: 1825

Answers (2)

tsolakp
tsolakp

Reputation: 5948

Seems like you are actually dealing with ranges for all the enums. The only difference between E and the rest is that the rest just have one value in the range.

I would change the enums to either take low/high or some kind of Range object.

Here is an example using IntStream.range which I like due to the ability of using all of its nice build in IntStream functionalities.

public enum SampleEnum {
    A( () -> IntStream.range(1, 2) ),
    B( () -> IntStream.range(2, 3) ),
    C( () -> IntStream.range(3, 4) ),
    D( () -> IntStream.range(4, 5) ),
    E( () -> IntStream.range(5, 101) );

    private Supplier<IntStream> rangeFactory = null;

    private SampleEnum(Supplier<IntStream> rangeFactory){
        this.rangeFactory = rangeFactory;
    }

    public IntStream getRange() {
        return rangeFactory.get();
    }
}

And here is an example of usage to check if a number is within a range:

    assertFalse( SampleEnum.A.getRange().anyMatch( i -> i == 0) );
    assertTrue( SampleEnum.A.getRange().anyMatch( i -> i == 1) );
    assertFalse( SampleEnum.A.getRange().anyMatch( i -> i == 2) );

    assertFalse( SampleEnum.C.getRange().anyMatch( i -> i == 2) );
    assertTrue( SampleEnum.C.getRange().anyMatch( i -> i == 3) );
    assertFalse( SampleEnum.C.getRange().anyMatch( i -> i == 4) );

    assertFalse( SampleEnum.E.getRange().anyMatch( i -> i == 4) );
    assertTrue( SampleEnum.E.getRange().anyMatch( i -> i == 5) );
    assertTrue( SampleEnum.E.getRange().anyMatch( i -> i == 100) );
    assertFalse( SampleEnum.E.getRange().anyMatch( i -> i == 101) );

Upvotes: 0

rgettman
rgettman

Reputation: 178363

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

Upvotes: 3

Related Questions