IDEA告警:Unnecessary unboxing ‘xxx.intValue()‘

简介: 显式编码拆箱已包装的原始数值。在Java5及以上的版本,拆箱是不必要的,可以安全地删除。那么 JDK5 到底做了啥

5.png

显式编码拆箱已包装的原始数值。在Java5及以上的版本,拆箱是不必要的,可以安全地删除。那么 JDK5 到底做了啥?


自动装箱(auto-boxing)与自动拆箱(auto-unboxing)


Java语言的基本类型都有包装(wrapper)类型。需要包装类型,是因为许多Java核心类库的API都是面向对象。如Java的容器类,就只支持引用类型。当需要一个能存储数值的容器类时,往往定义一个存储包装类对象的容器。


对基本类型的数值,需先将其转换为对应包装类,再存入容器。在Java程序中,这个转换可显式,也可隐式,后者即Java的自动装箱。

7.png



构造一个Integer类型ArrayList,向其中添加一个int值0。然后,获取该ArrayList的第0个元素,并作为int值返回,对应字节码:

6.png



当向泛型参数为Integer的ArrayList添加int值时,便用到自动装箱。字节码偏移量为10的指令,调用了Integer.valueOf,将int类型的值转换为Integer,再存储至容器类。


public static Integer valueOf(int i) {

   if (i >= IntegerCache.low && i <= IntegerCache.high)

       return IntegerCache.cache[i + (-IntegerCache.low)];

   return new Integer(i);

}


当请求的int值在某个范围内时,会返回缓存的Integer对象;在范围之外时,新建Integer对象。


参数java.lang.Integer.IntegerCache.high影响这里的IntegerCache.high。可配置该参数,扩大Integer缓存的范围。Java虚拟机参数**-XX:+AggressiveOpts**也会将IntegerCache.high调整至20000。


Java并不支持对IntegerCache.low的更改,对小于-128的整数,无法直接使用由Java核心类库所缓存的Integer对象。


25: invokevirtual java/lang/Integer.intValue:()I


当从泛型参数为Integer的ArrayList取出元素时,我们得到的实际上也是Integer对象。如果应用程序期待的是一个int值,那么就会发生自动拆箱,对应字节码偏移量为25的指令,调用Integer.intValue,直接返回Integer对象所存储的int值。

目录
相关文章
IDEA告警详解:Optional.isPresent can be replaced with functional-style expression
类似 if(Optional.isPresent()) 的条件语句,可以被重写成函数式风格。
132 0
IDEA告警详解:Optional.isPresent can be replaced with functional-style expression
|
缓存 Java Maven
IDEA 告警:Library source does not match the bytecode for class
IDEA 告警:Library source does not match the bytecode for class
1175 0
IDEA 告警:Library source does not match the bytecode for class
取消IDEA的Autowired对字段注解告警
取消IDEA的Autowired对字段注解告警
170 0
取消IDEA的Autowired对字段注解告警
|
API
IDEA告警:Can be replaced with ‘.values().stream()‘
IDEA告警:Can be replaced with ‘.values().stream()‘
464 0
IDEA告警:Can be replaced with ‘.values().stream()‘
|
存储
IDEA 告警Unpredictable ‘new BigDecimal()‘ call
IDEA 告警Unpredictable ‘new BigDecimal()‘ call
308 0
|
API
IDEA 告警:Stream API call chain can be simplified
IDEA 告警:Stream API call chain can be simplified
171 0
IDEA告警:Field can be converted to a local varible
IDEA告警:Field can be converted to a local varible
475 0
|
8月前
|
Java 编译器 Maven
使用intellij idea搭建SSM架构的maven项目 详细
使用intellij idea搭建SSM架构的maven项目 详细
127 4
|
7月前
|
IDE Oracle Java
day4:JDK、IntelliJ IDEA的安装和环境变量配置
【7月更文挑战第4天】🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
274 0
|
7月前
|
网络协议 安全 Linux
在IntelliJ IDEA中使用固定公网地址远程SSH连接服务器环境进行开发
在IntelliJ IDEA中使用固定公网地址远程SSH连接服务器环境进行开发
172 2

热门文章

最新文章