How can I do something like:
int a=5;
if(开发者_StackOverflow社区4<=a<=6){
}
in Java?
Make it two conditions:
int a=5;
if(4<=a && a<=6){
}
Apart from the obvious solution stated by others (if(4<=a && a<=6)
), you can use commons-lang's IntRange
:
Range range = new IntRange(4,6)
if (range.containsInteger(5)) {..}
It looks like a bit of an overkill, but depending on the situation (if it isn't as trivial) it can be very useful.
if(4 <= a && a <= 6) {
// do something
}
Of course, you could always write a function like this in some Util
class:
class Util {
public static boolean inclusiveBetween(int num, int a, int b) {
return num >= a && num <= b;
}
}
and then you can do something like
if(Util.inclusiveBetween(someResourceIntensiveOpReturningInt(), 4, 6)) {
// do things
}
You can't, I don't think. What's wrong with
int a = 5;
if(a >= 4 && a <= 6) {
}
? If you need to compare many different variables, put them in an array and sort the array, then compare the arrays.
You can do this. Its ugly, but can be very slightly faster.
int a = 5;
if(a - Integer.MIN_VALUE - 4 <= 2 - Integer.MIN_VALUE) {
}
This exploits the use of underflow to turn two comparisons into one. This can save about 1-2 nano-seconds. However, in some usecases it can cost the same amount, so only try it if you are trying to micro-tune a loop.
精彩评论