Java 中的 Range(min, max, value) 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10973028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Range(min, max, value) function in Java
提问by Ivan Seidel
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?
我在谷歌上没有找到。是因为它不存在吗?
采纳答案by Bohemian
You could create a typed Range
class that has a within
method:
您可以创建一个Range
具有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 a group of tests, you could reuse your range
object for all tests.
如果一组测试的 min 和 max 相同,则您可以range
在所有测试中重复使用您的对象。
FWIW, this seems kinda handy!
FWIW,这似乎有点方便!
回答by Dave Newton
Apache Commons Lang has a number of Range implementations, including NumberRange.
Apache Commons Lang 有许多 Range 实现,包括NumberRange。
Commons Lang 3 has a generic implementation.
Commons Lang 3 有一个通用的实现。
回答by Michael Borgwardt
um...
嗯...
value >= min && value <= max
surely if you really need a function for that you can easily write it yourself?
当然,如果您真的需要一个函数,您可以轻松地自己编写它吗?
回答by Dancrumb
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
一个“合理”的地方是在 Math 模块中,但因为它在表达式中很简单地表达
min < value && value < max
it seems a little excessive.
好像有点过分了。
回答by Nanda Ramanujam
public static boolean withinRange(min, max, value){
return (value >= min && value <= max);
}