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?
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!
Apache Commons Lang has a number of Range implementations, including NumberRange .
Commons Lang 3 has a generic implementation .
um...
value >= min && value <= max
surely if you really need a function for that you can easily write it yourself?
It doesn't exist.
A 'sensible' place for it would be in the Math module, but since it's quite simply expressed in the expression
min < value && value < max
it seems a little excessive.
public static boolean withinRange(min, max, value){
return (value >= min && value <= max);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.