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。

  • 相关阅读:
    使用docker搭建nginx集群,实现负载均衡
    机器重启以后,主从出现报错:ERROR 1872 (HY000): Slave failed to initialize relay log info structure from the repos
    Slave_SQL_Running: No mysql同步故障解决方法
    docker搭建MySQL主从集群
    Linux下如何查看版本信息
    Docker中使用CentOS7镜像
    在 CentOS 上安装及使用 VirtualBox
    Docker Machine 安装使用教程
    main主函数
    is and ==
  • 原文地址:https://www.cnblogs.com/jxd283465/p/14634751.html
Copyright © 2011-2022 走看看