Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range(min, max, value) function in Java

Tags:

java

methods

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 didn't find it on Google. Is that because it doesn't exist?

like image 674
Ivan Seidel Avatar asked Jun 10 '12 22:06

Ivan Seidel


1 Answers

You could create a typed Range class that has a within method:

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 a group of tests, you could reuse your range object for all tests.

FWIW, this seems kinda handy!

like image 164
Bohemian Avatar answered Oct 09 '22 19:10

Bohemian