Range function (min, max, value) in Java

Sometimes we write unnecessary code. My question is pretty simple: is there a method like the following?

/** @return true if a given value is inside the range. */
public static boolean range(min, max, value)

I did not find it on Google. Is it because it does not exist?

+5
source share
4 answers

You can create a typed Rangeclass with a method within:

public class Range<T extends Comparable<T>> {

    private final T min;
    private final T max;

    public Range( T min, T max ) {
        this.min = min;
        this.max = max;
    }

    public boolean within( T value ) {
        return min.compareTo(value) <= 0 && max.compareTo(value) >= 0;
    }
}

If min and max were the same for the test group, you can reuse your object Rangefor all tests.

FWIW, this seems convenient!

+3
source

Apache Commons Lang has a number of Range implementations, including NumberRange .

Commons Lang 3 has a common implementation .

+3
source

...

value >= min && value <= max

, , ?

+2

.

A β€œreasonable” place for it would be in the Math module, but since it is quite simply expressed in the expression

min < value && value < max

seems a little excessive.

+2
source

All Articles