Java Integer及int装箱拆箱对比
作者:bf378 时间:2023-04-22 04:21:11
示例代码:
class BoxIntInteger {
public static void main(String[] args) {
Integer a = new Integer(10111);
int b = 10111;
boolean equal1 = a == b;
boolean equal2 = a.equals(b);
System.out.println(equal1);
System.out.println(equal2);
}
}
反编译字节码:
public static void main(String args[])
{
Integer a = new Integer(10111);
int b = 10111;
boolean equal1 = a.intValue() == b;
boolean equal2 = a.equals(Integer.valueOf(b));
System.out.println(equal1);
System.out.println(equal2);
}
1:可以看出对于Integer与int使用==比较大小的话,优先Integer拆箱。
2: 如果使用equals比较大小的话,则int装箱。
提示:对于Integer与int之间大小比较优先使用equals比较,否则容易出现空指针,例如:
Integer c= null;
System.out.println(c==1);
原因:由于Integer需要调用intValue进行拆箱,因而空指针。
Integer与Integer必须使用equals方法比较,这个就不必解释了。但是通常我们可以看先Integer与Integer之间使用==也可以正确比较,原因是:Integer对于-128到127之间的数字在缓存中拿,不是创建新对象。
缓存获取数据源码:java.lang.Integer#valueOf(int)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
来源:https://www.cnblogs.com/leodaxin/p/9088036.html
标签:java,Integer,int
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决MyEclipse出现the user operation is waiting的问题
2022-05-02 21:44:07
![](https://img.aspxhome.com/file/2023/0/64750_0s.gif)
C#分布式事务的超时处理实例分析
2022-06-16 03:11:28
Android自定义view实现输入控件
2022-12-11 10:08:06
![](https://img.aspxhome.com/file/2023/3/137453_0s.gif)
Windows下Java环境配置的超详细教程
2021-12-18 19:19:16
![](https://img.aspxhome.com/file/2023/4/62154_0s.jpg)
android 7自定义相机预览及拍照功能
2023-01-29 06:56:34
Android沉浸式状态栏的实现代码
2023-08-21 05:52:08
![](https://img.aspxhome.com/file/2023/3/125403_0s.jpg)
关于java 图形验证码的解决方法
2023-08-09 15:21:19
Java 导出Excel增加下拉框选项
2021-10-13 07:58:50
SpringBoot集成POI实现Excel导入导出的示例详解
2022-12-05 19:09:10
![](https://img.aspxhome.com/file/2023/0/87350_0s.png)
SpringBoot整合Swagger的方法示例
2021-05-29 02:42:16
Android 中通过ViewDragHelper实现ListView的Item的侧拉划出效果
2021-08-14 18:37:46
![](https://img.aspxhome.com/file/2023/2/108252_0s.gif)
WPF快速入门教程之绑定Binding
2021-10-10 15:32:00
![](https://img.aspxhome.com/file/2023/3/89793_0s.jpg)
spring boot集成p6spy的最佳实践
2023-04-11 23:40:36
![](https://img.aspxhome.com/file/2023/8/72908_0s.png)
springmvc不进入Controller导致404的问题
2023-03-18 01:29:20
![](https://img.aspxhome.com/file/2023/2/62102_0s.png)
如何利用IDEA搭建SpringBoot项目整合mybatis实现简单的登录功能
2022-01-15 06:14:59
![](https://img.aspxhome.com/file/2023/9/61849_0s.png)
C++联合体union用法实例详解
2023-12-01 16:34:00
Android系统中的蓝牙连接程序编写实例教程
2023-09-06 08:59:01
ubuntu环境下反编译android apk的方法
2022-08-09 13:41:41
![](https://img.aspxhome.com/file/2023/4/129054_0s.png)
聊聊如何打印GC日志排查的问题
2023-01-22 22:10:56
![](https://img.aspxhome.com/file/2023/8/97828_0s.jpg)
java中初始化MediaRecorder的实现方法
2023-11-29 03:54:52