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实例。

看到这儿之后,上面的结果就显而易见了。

最新文章

  1. iOS开发--弹窗多选、单选框架
  2. 双系统win+ubuntu无法访问win的盘符
  3. 转:python webdriver API 之cookie 处理
  4. VS活动解决方案平台
  5. Java之数组array和集合list、set、map
  6. Java基础知识强化之集合框架笔记69:Collections类之ArrayList存储自自定义对象并排序的案例
  7. react native mac install
  8. 网络流(最大流) HDU 1565 方格取数(1) HDU 1569 方格取数(2)
  9. 原生JS Ajax 请求
  10. ASP.NET Core - Razor 页面简介
  11. hive分区(partition)
  12. fhs文件系统层级结构
  13. 解决在onCreate()过程中获取View的width和Height为0的方法
  14. linux环境部署python3+django
  15. 收藏:SQL Server 数据库改名
  16. vs2017配置pthread.h的方法
  17. Webapi通过报文获取post上来的数据
  18. Java时间格式转换工具类
  19. Android------底部导航栏BottomNavigationBar
  20. 我是如何在SQLServer中处理每天四亿三千万记录的(转)

热门文章

  1. Java构建工具_Ant详解
  2. linux c++ 文件获取md5
  3. .NET面试题(二)
  4. VUE详解
  5. EF(EntityFramework) Migrations 迁移
  6. Nginx日志深入详解
  7. python字符串操作,以及对应的C#实现
  8. Atitit. 软件开发中的管理哲学--一个伟大的事业必然是过程导向为主 过程导向 vs 结果导向
  9. [gj]狮子经典语录
  10. ToStringBuilder学习(三):readResolve()方法与序列化