我注意到在Java 8中,类
BigInteger
新增了一个方法: intValueExact()
。
我的问题是:为什么?
BigInteger bigInt = ... ;
bigInt.intValueExact();
BigInteger
已经有intValue()
方法。 intValueExact()
的目的是在您的BigInteger
不持有精确的int
值时抛出错误,但我的问题是:如何可能为BigInteger
赋予一个不等于精确int
的值?有人能提供一个例子,说明这个方法何时会抛出ArithmeticException
吗?
BigInteger
太大而无法适应int
,该怎么办? - MysticialBigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE)
BOOM 的翻译:BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE)
意为将整数最大值转换成大整数类型并加一,当结果超出了大整数类型的范围时会导致计算错误。 - yshavitBigInteger
不能容纳比int
更大的值,那么使用BigInteger
的意义是什么? - Cole TobinBigInteger
可以保存比int
更大的值。@yshavit的评论是一个示例场景,当调用intValueExact()
时会抛出错误,这也是原始问题所问的。 - ryvantage