如何用Java表示范围? [英] How can I represent a range in Java?

查看:443
本文介绍了如何用Java表示范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个整数应该在以下范围内: [0 ... 2147483647]

Let's say an integer should be within the range: [0...2147483647]

我想要检查整数变量是否在此范围内。我知道它可以通过简单的if-else语句来完成,但有没有更有效的方法来检查它是否在范围内?

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?

我宁愿不这样做:

if (foo >= 0 && foo <= 2147483647) 
{
    // do something
}


推荐答案

Apache Commons Lang有一个 范围

Apache Commons Lang has a Range class for doing arbitrary ranges.

Range<Integer> test = Range.between(1, 3);
System.out.println(test.contains(2));
System.out.println(test.contains(4));

Guava 范围 具有类似的API。

Guava Range has similar API.

如果您只是想检查数字是否适合长值或int值,您可以尝试通过 BigDecimal 。 longValueExact intValueExact 的方法如果值对于那些精度而言太大,则抛出异常。

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.

这篇关于如何用Java表示范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆