jdk 8 时区 转换
在博客文章“ Java中Long到Int的精确转换 ”中,我讨论了使用Math.toIntExact(Long)将Long
精确地转换为int
或者如果无法缩小转换范围则抛出ArithmeticException 。
JDK 8引入了该方法, JDK 8还向BigInteger类引入了类似的缩小转换方法。 这些BigInteger
方法是本文的主题。
BigInteger
在JDK 8中添加了四个新的“精确”方法:
- byteValueExact() –尽可能将
BigInteger
值准确转换为byte
- shortValueExact() –如果可能,将
BigInteger
值转换为short
- intValueExact() –尽可能将
BigInteger
值准确转换为int
- longValueExact() –如果可能,将
BigInteger
值精确转换为long
如上所述,通过JDK 8添加到BigInteger
的这四个“精确”方法中的每一个都可以将BigInteger
的值缩小到方法名称中的数据类型(如果可能)。 由于所有这些类型( byte
, short
, int
和long
)的范围都小于BigInteger
,因此在任何情况下, BigDecimal
的值都可能比这四种类型中的任何一种都大。 在这种情况下,所有这四个“精确”方法都将引发ArithmeticException
而不是悄悄地“将”较大的值“强制”为较小的表示形式(在大多数情况下,这通常是无意义的数字)。
可以在GitHub上找到使用这些方法的示例。 执行这些示例时,输出如下所示:
===== Byte =====
125 => 125
126 => 126
127 => 127
128 => java.lang.ArithmeticException: BigInteger out of byte range
129 => java.lang.ArithmeticException: BigInteger out of byte range
===== Short =====
32765 => 32765
32766 => 32766
32767 => 32767
32768 => java.lang.ArithmeticException: BigInteger out of short range
32769 => java.lang.ArithmeticException: BigInteger out of short range
===== Int =====
2147483645 => 2147483645
2147483646 => 2147483646
2147483647 => 2147483647
2147483648 => java.lang.ArithmeticException: BigInteger out of int range
2147483649 => java.lang.ArithmeticException: BigInteger out of int range
===== Long =====
9223372036854775805 => 9223372036854775805
9223372036854775806 => 9223372036854775806
9223372036854775807 => 9223372036854775807
9223372036854775808 => java.lang.ArithmeticException: BigInteger out of long range
9223372036854775809 => java.lang.ArithmeticException: BigInteger out of long range
在带有JDK 8的BigInteger
添加这些“精确”方法是一种受欢迎的方法,因为与数字缩小和溢出相关的错误可能很细微。 拥有一种简单的方法来获得“精确的”缩小是很好的,否则将无法通过异常使这种缩小变得明显。
翻译自: https://www.javacodegeeks.com/2018/06/biginteger-exact-narrowing-conversion-methods.html
jdk 8 时区 转换