BigInteger在Java8里增加了一组方法:

1
2
3
public byte byteValueExact()
public int intValueExact()
public long longValueExact()

这些方法后面都有Exact(),在老的JDK版本中,已经有了byteValue,intValue,longValue()为什么还要再增加这些方法呢?
因为在原来的方法中,如果BigInteger的值溢出了要目标类型的范围,是不会有任何提示的,那么我们的程序很可能在一个很隐蔽的错误下执行,没有任何错误输出,但是程序依然会继续执行,这种错误很难很难查。。。。。(大家可以想象一下,一个数值被突然改变了,不是很仔细的看,很难看出来),
有了新的XXXExact()方法,这一切都好办了,XXXExact()方法会在溢出的时候,抛出一个异常

1
2
3
4
5
6
public long longValueExact({
    if (mag.length <= && bitLength(<= 63)
        return longValue();
    else
        throw new ArithmeticException("BigInteger out of long range");
}

这样,我们就是可以在溢出时得到一个通知,进行处理。

相关文章:

  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2021-06-22
  • 2021-06-12
猜你喜欢
  • 2021-12-04
  • 2022-12-23
  • 2021-10-15
  • 2022-12-23
  • 2021-10-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案