JDK 8附带所有令人眼前一亮的 东西 ( lambda表达式 , 流 , Optional ,新的Date / Time API等)来分散我的注意力 ,我并没有过多注意添加方法Math.toIntExact() 。 但是,这种小的添加本身可能会非常有用。

Math.toIntExact(long)的Javadoc文档指出:“返回long参数的值; 如果值溢出int则引发异常。” 这在给定或已经具有Long且需要调用期望int的API的情况下特别有用。 当然,最好是将API更改为使用相同的数据类型,但这有时是无法控制的。 当需要将Long强制为int值时,则存在整数溢出的可能性,因为Long的数值可能比int可以准确表示的数值大。

如果有人告诉给定的Long永远不会大于int可以容纳的Math.toIntExact(Long) ,则静态方法Math.toIntExact(Long)尤其有用,因为如果出现这种“异常”情况,它将抛出未经检查的ArithmeticException ,这很明显发生“例外”情况。

当Long.intValue()用于从Long获取整数时,如果发生整数溢出,则不会引发异常。 而是提供了一个整数,但是由于整数溢出,该值很少有用。 在几乎每种可能的情况下,遇到运行时异常都会向整数警报发出警报的情况要比让软件继续错误地使用溢出数更好。

如在示出之间的差异的第一步Long.intValue()Math.toIntExact(Long) ,下面的代码生成的范围内Long为5的值小于Integer.MAX_VALUE的至5以上Integer.MAX_VALUE

包含Integer.MAX_VALUELong的生成范围

/*** Generate {@code Long}s from range of integers that start* before {@code Integer.MAX_VALUE} and end after that* maximum integer value.** @return {@code Long}s generated over range includes*    {@code Integer.MAX_VALUE}.*/
public static List<Long> generateLongInts()
{final Long maximumIntegerAsLong = Long.valueOf(Integer.MAX_VALUE);final Long startingLong = maximumIntegerAsLong - 5;final Long endingLong = maximumIntegerAsLong + 5;return LongStream.range(startingLong, endingLong).boxed().collect(Collectors.toList());
}

下一个代码清单显示了两种方法,这些方法演示了前面提到的两种从Long获取int方法。

使用Long.intValue()Math.toIntExact(Long)

/*** Provides the {@code int} representation of the provided* {@code Long} based on an invocation of the provided* {@code Long} object's {@code intValue()} method.** @param longRepresentation {@code Long} for which {@code int}*    value extracted with {@code intValue()} will be returned.* @return {@code int} value corresponding to the provided*    {@code Long} as provided by invoking the method*    {@code intValue()} on that provided {@code Long}.* @throws NullPointerException Thrown if the provided long*    representation is {@code null}.*/
public static void writeLongIntValue(final Long longRepresentation)
{out.print(longRepresentation + " =>       Long.intValue() = ");try{out.println(longRepresentation.intValue());}catch (Exception exception){out.println("ERROR - " + exception);}
}/*** Provides the {@code int} representation of the provided* {@code Long} based on an invocation of {@code Math.toIntExact(Long)}* on the provided {@code Long}.** @param longRepresentation {@code Long} for which {@code int}*    value extracted with {@code Math.toIntExact(Long)} will be*    returned.* @return {@code int} value corresponding to the provided*    {@code Long} as provided by invoking the method*    {@code Math.toIntExact)Long} on that provided {@code Long}.* @throws NullPointerException Thrown if the provided long*    representation is {@code null}.* @throws ArithmeticException Thrown if the provided {@code Long}*    cannot be represented as an integer without overflow.*/
public static void writeIntExact(final Long longRepresentation)
{out.print(longRepresentation + " => Math.toIntExact(Long) = ");try{out.println(Math.toIntExact(longRepresentation));}catch (Exception exception){out.println("ERROR: " + exception);}
}

当以上代码使用在先前代码清单中构建的Long的范围( GitHub上提供完整代码 )执行时,输出如下所示:

2147483642 =>       Long.intValue() = 2147483642
2147483642 => Math.toIntExact(Long) = 2147483642
2147483643 =>       Long.intValue() = 2147483643
2147483643 => Math.toIntExact(Long) = 2147483643
2147483644 =>       Long.intValue() = 2147483644
2147483644 => Math.toIntExact(Long) = 2147483644
2147483645 =>       Long.intValue() = 2147483645
2147483645 => Math.toIntExact(Long) = 2147483645
2147483646 =>       Long.intValue() = 2147483646
2147483646 => Math.toIntExact(Long) = 2147483646
2147483647 =>       Long.intValue() = 2147483647
2147483647 => Math.toIntExact(Long) = 2147483647
2147483648 =>       Long.intValue() = -2147483648
2147483648 => Math.toIntExact(Long) = ERROR: java.lang.ArithmeticException: integer overflow
2147483649 =>       Long.intValue() = -2147483647
2147483649 => Math.toIntExact(Long) = ERROR: java.lang.ArithmeticException: integer overflow
2147483650 =>       Long.intValue() = -2147483646
2147483650 => Math.toIntExact(Long) = ERROR: java.lang.ArithmeticException: integer overflow
2147483651 =>       Long.intValue() = -2147483645
2147483651 => Math.toIntExact(Long) = ERROR: java.lang.ArithmeticException: integer overflow

高亮显示的行指示代码处理Long的值等于Integer.MAX_VALUE的代码。 之后,显示的Long表示比Integer.MAX_VALUE多一个的Long并显示尝试使用Long.intValue()Math.toIntExact(Long)将该Long转换为int的结果。 Long.intValue()方法遇到整数溢出,但不会引发异常,而是返回负数-2147483648Math.toIntExact(Long)方法在整数溢出时不返回任何值,而是引发ArithmeticException与信息性消息“整数溢出”。

Math.toIntExact(Long)方法的重要性不如JDK 8引入的许多功能重要,但是它对于避免有时可能难以诊断的整数溢出相关的错误类型很有用。

翻译自: https://www.javacodegeeks.com/2018/06/exact-conversion-long-to-int-java.html

Java中Long到Int的精确转换相关推荐

  1. Java中 char和int之间的转换

    1.int 转换成char: int  n = 1;                 char ch = (char)(n + '0'); 这样打印出来ch的值为1;                 ...

  2. Java中long和int互相转换,不改变原有数据

    Java中long和int互相转换,不改变原有数据 文章目录 Java中long和int互相转换,不改变原有数据 测试方法,及封装好的方法 封装好之后的方法 测试方法,及封装好的方法 @Test pu ...

  3. java中string和int的相互转换

    java中string和int的相互转换 int -> String int i=12345; String s=""; 核心:s=i+""; Strin ...

  4. Java中String转int类型出现的问题及解决方式

    一般在Java中String转为Int主要有两种方法: 1. Integer.parseInt(str); 2. Integer.valueOf(str); ps:两者的不同之处: Integer.p ...

  5. java中各进制之间的转换(十进制转十六进制、十进制转二进制、二进制转十进制、二进制转十六进制)...

    在java编辑中有没有遇到经常需要进行java中各进制之间的转换(十进制转十六进制.十进制转二进制.二进制转十进制.二进制转十六进制)的事情呢?下面我们就来分析一下各自是怎么转换的: [java] / ...

  6. Javascript中char和int的互相转换的代码(转载)

    Javascript中char和int的互相转换的代码 // Converts an integer (unicode value) to a char function itoa(i) {      ...

  7. Java中char和int相互转换

    char转int的方法 方法一(直接转) 使用Character.getNumericValue(char)方法 public static void main(String[] args) {cha ...

  8. java中double转int

    java中double转int    (1). (int) 2.9 = 2;//不进行四舍五入 (2).  四舍五入:new BigDecimal("1.5").setScale( ...

  9. java中char与int的转换问题

    众所周知,java中int型和char型数据不像c语言中那样可以任意转换,即不可以将一个int型变量自动转换为char型,如下面代码中的演示: public class TestSort{  publ ...

最新文章

  1. mysql 打开文件数_MySQL打开的文件描述符限制
  2. 计算机及网络应用基础思维导图_计算机基础/算法/面试题 PDF+思维导图下载
  3. 英属哥伦比亚大学计算机科学,细致用心 终获英属哥伦比亚大学计算机科学专业offer...
  4. 欢迎参与2020年云栖大会——引领企业基础设施云化
  5. 什么是跨域?什么是CSRF?
  6. 使用Spring和Hibernate进行集成测试有多酷
  7. Airbnb搜索:Embedding表示学习
  8. 超越Excel,这才是报表的正确打开方式,可惜90%的人都没用过
  9. 安装运行okvis odometry
  10. android画布橡皮,Android 图片涂鸦橡皮擦功能
  11. 如果公司不用绩效考核,用什么
  12. php 忽略 deprecated,php Deprecated 解决办法
  13. 代码随想录第二十一天 LeetCode 530、501、236
  14. 开正式发票到底谁交税
  15. Android网络框架okhttp3简单封装
  16. 论文导读:Deep Attentive Learning for Stock Movement Prediction From Social Media Text and Company Correl
  17. 【数据结构与算法】线性表的查找
  18. 翻译——现金流的时间性导致NPV与IRR的矛盾:炼油公司资本预算决策案例
  19. bootStrap-table之全选反选
  20. c语言 编写 简单万年历

热门文章

  1. 3、数据库中的字符集和校对集
  2. Mysql调优你不知道这几点,就太可惜了
  3. 一篇文章了解RPC框架原理
  4. JavaFX官方教程(十四)之转换,动画和视觉效果教程的源代码
  5. mybatis入门(一)之基础安装
  6. 【FTP】发布FTP服务器
  7. 马踏棋盘算法(骑士周游)
  8. php渐变字,jQuery_jQuery实现的立体文字渐变效果,先截两个图看看: 效果很 - phpStudy...
  9. python isodd奇偶_Python这些位运算的妙用,绝对让你大开眼界
  10. python3安装mysql模块_Python安装MySQL库详解,步骤及错误的解决方法