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。

  • 相关阅读:
    在jupyter notebook 添加 conda 环境的操作详解
    MySQL plugin 'caching_sha2_password' cannot be loaded
    mathtype公式转latex代码
    博客园如何插入latex公式
    pip使用国内源安装
    python读取XML格式文件并转为json格式
    7.用生成函数求解下列递归方程 f(n)=2f(n/2)+cn n>1 f(1)=0 n=1
    用生成函数求解下列递归方程 f(n)=2f(n-1)+1 n>1 f(1)=2 n=1
    《将博客搬至CSDN》
    111111111111111111
  • 原文地址:https://www.cnblogs.com/jxd283465/p/14634751.html
Copyright © 2011-2022 走看看