Integer Cache

废话不多说----->直接上代码:

public class IntegerDemo {
public static void main(String[] args) {
Integer numA = 127;
Integer numB = 127;

Integer numC = 128;
Integer numD = 128;

System.out.println("numA == numB : "+ (numA == numB));
System.out.println("numC == numD : "+ (numC == numD));
}
}

结果:

numA == numB : true
numC == numD : false

What?这个输出结果怎么跟以往的认知有所出入呢?在我们的代码“Integer numA = 127”中,编译器会把基本数据的“自动装箱”(autoboxing)成包装类,所以这行代码就等价于“Integer numA = Integer.valueOf(127)”了,这样我们就可以进入valueOf方法查看它的实现原理。

 Integer类的源码

  private static class IntegerCache {
static final int low = -128;
static final int high = 127;
static final Integer cache[];
......
} public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

从上面的源码可以看到,valueOf方法会先判断传进来的参数是否在IntegerCache的low与high之间,如果是的话就返回cache数组里面的缓存值,不是的话就new Integer(i)返回。

----------------------------------------------------------------------------------------------------------------------------------------

那我们再往上看一下IntegerCache,它是Integer的内部静态类,low默认是-128,high的值默认127,但是high可以通过JVM启动参数XX:AutoBoxCacheMax=size来修改(如图),如果我们按照这样修改了,然后再次执行上面代码,这时候2次输出都是true,因为缓存的区间变成-128~200了。

最新文章

  1. Python爬取代理ip
  2. cx_Oracle 中文乱码问题解决
  3. 以下css可以清除浮动
  4. python 不得不知的第三方库以及常用安装包
  5. PostQuitMessage, PostThreadMessage( WM_QUIT )
  6. css中 中文字体(font-family)的标准英文名称
  7. Android 自带 camera 详解
  8. Oracle数据库的启动和关闭
  9. 随心测试_数据库_002 &lt;数据库系统组成&gt;
  10. angular.isDate()
  11. Day2数据结构和算法
  12. vue axios数据请求get、post方法的使用
  13. kmp算法python实现
  14. 在eclipse中使用Tomcat时出现Could not publish server ...错误
  15. C#winform窗体实现对sql server数据库的增删改查
  16. js 格式为2018-08-25 11:46:29 的日期比较方法
  17. linux用户管理 用户和用户组信息
  18. [LeetCode&amp;Python] Problem 122. Best Time to Buy and Sell Stock II
  19. mysql用户创建与授权
  20. LeetCode 49 Group Anagrams(字符串分组)

热门文章

  1. Method Swizzling以及AOP编程:在运行时进行代码注入-b
  2. com.sun.jdi.InvocationException occurred invoking method 异常
  3. 【转载】lvs为何不能完全替代DNS轮询
  4. 基于bootstrap_后台管理
  5. Nova虚拟机启动提示libvirtError
  6. DB主从一致性的几种解决方法
  7. UR#34. 多项式乘法
  8. Java的编程逻辑--15章 并发基础
  9. Spring中的AOP(学习笔记)
  10. https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py