Integer Cache(带你脱坑)
2024-08-30 12:56:57
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了。
最新文章
- Python爬取代理ip
- cx_Oracle 中文乱码问题解决
- 以下css可以清除浮动
- python 不得不知的第三方库以及常用安装包
- PostQuitMessage, PostThreadMessage( WM_QUIT )
- css中 中文字体(font-family)的标准英文名称
- Android 自带 camera 详解
- Oracle数据库的启动和关闭
- 随心测试_数据库_002 <;数据库系统组成>;
- angular.isDate()
- Day2数据结构和算法
- vue axios数据请求get、post方法的使用
- kmp算法python实现
- 在eclipse中使用Tomcat时出现Could not publish server ...错误
- C#winform窗体实现对sql server数据库的增删改查
- js 格式为2018-08-25 11:46:29 的日期比较方法
- linux用户管理 用户和用户组信息
- [LeetCode&;Python] Problem 122. Best Time to Buy and Sell Stock II
- mysql用户创建与授权
- LeetCode 49 Group Anagrams(字符串分组)
热门文章
- Method Swizzling以及AOP编程:在运行时进行代码注入-b
- com.sun.jdi.InvocationException occurred invoking method 异常
- 【转载】lvs为何不能完全替代DNS轮询
- 基于bootstrap_后台管理
- Nova虚拟机启动提示libvirtError
- DB主从一致性的几种解决方法
- UR#34. 多项式乘法
- Java的编程逻辑--15章 并发基础
- Spring中的AOP(学习笔记)
- https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py