Integer自动装拆箱
2024-09-28 03:13:55
public static void main(String[] args) {
Integer a1 = 1;
Integer a2 = 1;
Integer b1 = 127;
Integer b2 = 127;
Integer c1 = 128;
Integer c2 = 128;
Integer d1 = 321;
Integer d2 = 321;
System.out.println(a1 == a2);
System.out.println(b1 == b2);
System.out.println(c1 == c2);
System.out.println(d1 == d2);
}
结果:
true
true
false
false
原因:
首先我们来看一下JDK源码是如何实现Integer.valueOf()方法的;
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
其中IntegerCache是Integer类中的一个内部类,其代码比较简单,如下所示:
private static class IntegerCache {
private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
如果传入的int在[-128~127],那就尝试看前面的缓存中有没有打过包的相同的值,如果有就直接返回,否则就创建一个Integer实例。
看到这儿之后,上面的结果就显而易见了。
最新文章
- iOS开发--弹窗多选、单选框架
- 双系统win+ubuntu无法访问win的盘符
- 转:python webdriver API 之cookie 处理
- VS活动解决方案平台
- Java之数组array和集合list、set、map
- Java基础知识强化之集合框架笔记69:Collections类之ArrayList存储自自定义对象并排序的案例
- react native mac install
- 网络流(最大流) HDU 1565 方格取数(1) HDU 1569 方格取数(2)
- 原生JS Ajax 请求
- ASP.NET Core - Razor 页面简介
- hive分区(partition)
- fhs文件系统层级结构
- 解决在onCreate()过程中获取View的width和Height为0的方法
- linux环境部署python3+django
- 收藏:SQL Server 数据库改名
- vs2017配置pthread.h的方法
- Webapi通过报文获取post上来的数据
- Java时间格式转换工具类
- Android------底部导航栏BottomNavigationBar
- 我是如何在SQLServer中处理每天四亿三千万记录的(转)