zoukankan      html  css  js  c++  java
  • 【Java】Integer类型比较

       public static void main(String[] args) {
            Integer x = 128, y = 128;
            System.out.println(x == y);   false
            Integer s = 127, t = 127;
            System.out.println(s == t);   true
        }

    先说结论

    Integer的比较在【-128,127】之间的数时,俩对象“==”返回true

    不在这一范围的返回false。

    具体原因看Integer源码

        private static class IntegerCache {
            static final int low = -128;
            static final int high;
            static final Integer cache[];
    
            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;
            }
    
            private IntegerCache() {}
        }

    在integer中有个静态内部类定义了缓存池,范围是-128到127之间,在类加载的期间就已经完成,需要的时候直接指向,省去了构造对象的时间,提高了效率。

    实际上Integer s = 127, t = 127;中s和t指向的是同一对象,“==”比较对象的地址是否相等,故打印出true。

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

    上述代码可以看出当int i自动装箱的时候判断了i的范围是否在-128到127之间,如果是则直接返回缓存的对象,

    如果不是则new了一个新对象。

    所以Integer x = 128, y = 128;实际上是x和y分别new了Integer对象,分别指向了不同对象的地址,故打印出false。

  • 相关阅读:
    AcWing 2476. 树套树(线段树套splay)
    LeetCode 1191 K 次串联后最大子数组之和
    LeetCode 668 乘法表中第k小的数
    Java003-String字符串
    云原生CD工具spinnaker部署(容器化灰度发布)
    刷题日记
    8.22 校内模拟赛 题解报告
    关于 CDQ分治(复习)
    解题营_数论
    解题营_动规
  • 原文地址:https://www.cnblogs.com/jxd283465/p/14634751.html
Copyright © 2011-2022 走看看