Let's say an integer should be within the range: [0...2147483647]
I want to check whether an integer variable falls within this range. I know it can be accomplished by a simple if-else statement, but is there a more efficient way to check whether it's within the range?
I'd rather not do this:
if (foo >= 0 && foo <= 2147483647)
{
// do something
}
解决方案
Apache Commons Lang has a Range class for doing arbitrary ranges.
Range test = Range.between(1, 3);
System.out.println(test.contains(2));
System.out.println(test.contains(4));
Guava Range has similar API.
If you are just wanting to check if a number fits into a long value or an int value, you could try using it through BigDecimal. There are methods for longValueExact and intValueExact that throw exceptions if the value is too big for those precisions.