ArrayList<Integer>使用==比较值是否相等出现 -129!=-129的情况思考

面试题 02.06. 回文链表这个题目中我是用ArrayList存储链表中的值,然后使用双指针来判断是否为回文

但是测试用例中存在有超过[-128,127]的数字,由于泛型类型使用到了Integer,由于Integer是包装类型,但是没有使用equals方法比较,所以出现-129!=-129的问题

 

观察Integer源码

  • valueOf方法:
1    public static Integer valueOf(int i) {
2         if (i >= IntegerCache.low && i <= IntegerCache.high)
3             return IntegerCache.cache[i + (-IntegerCache.low)];
4         return new Integer(i);
5     }
  • 内部缓存IntegerCache数组:
复制代码
 1 private static class IntegerCache {
 2         static final int low = -128;
 3         static final int high;
 4         static final Integer cache[];
 5 
 6         static {
 7             // high value may be configured by property
 8             int h = 127;
 9             String integerCacheHighPropValue =
10                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
11             if (integerCacheHighPropValue != null) {
12                 try {
13                     int i = parseInt(integerCacheHighPropValue);
14                     i = Math.max(i, 127);
15                     // Maximum array size is Integer.MAX_VALUE
16                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
17                 } catch( NumberFormatException nfe) {
18                     // If the property cannot be parsed into an int, ignore it.
19                 }
20             }
21             high = h;
22 
23             cache = new Integer[(high - low) + 1];
24             int j = low;
25             for(int k = 0; k < cache.length; k++)
26                 cache[k] = new Integer(j++);
27 
28             // range [-128, 127] must be interned (JLS7 5.1.7)
29             assert IntegerCache.high >= 127;
30         }
复制代码

结论:

  在范围内使用缓存,当在缓存范围内使用“==”比较,比较缓存数组中的地址,自然相等。

  在范围外比较,new Integer对象,使用“==”比较包装类,自然地址不等。

posted @   yky_xukai的胡思乱想  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示