Integer类小细节随笔记录
先看一段简单的代码:
1 2 3 4 5 6 7 8 | Integer v1 = Integer.valueOf( 12 ); Integer v2 = Integer.valueOf( 12 ); Integer v3 = Integer.valueOf( 129 ); Integer v4 = Integer.valueOf( 129 ); System.out.println(v1 == v2); System.out.println(v3 == v4); |
输出结果是啥呢?第一个是 true,第二个是false。
为啥呢?
1 2 3 4 5 | public static Integer valueOf( int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } |
看源代码得知,当 i 在默认条件下(-127到128)之间,从缓存中取值,否则重新 new 一个 Integer 对象。详细代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | static { // high value may be configured by property int h = 127 ; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty( "java.lang.Integer.IntegerCache.high" ); if (integerCacheHighPropValue != null ) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127 ); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) - 1 ); } catch ( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1 ]; int j = low; for ( int k = 0 ; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127 ; } |
所以,我们上述的代码运行结果为 true 和 false。Integer(12) 两次都是取的缓存的值,129两次分别重新创建对象。
不过从注释上可以了解到,可以调整jvm参数来定缓存数组的大小。
1 2 | * The cache is initialized on first usage. The size of the cache * may be controlled by the { @code -XX:AutoBoxCacheMax=<size>} option. |
再次重新运行,输出结果都为 true。因为把缓存集合的空间大小调整到了 130 + 127 ,所以 129 也从缓存中取。再试一次 取131 对比。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?