zoukankan      html  css  js  c++  java
  • Integer 类型比较大小

    == 比较 Integer 大小

    Integer n1 = 127;
    Integer n2 = 127;
    System.out.println(n1 == n2);       // true
    System.out.println(n1.equals(n2));  // true
    
    Integer n1 = 128;
    Integer n2 = 128;
    System.out.println(n1 == n2);       // false
    System.out.println(n1.equals(n2));  // true
    

    首先Integer n1 = 127; 这种赋值方式,是会进行装箱操作的;
    下面我们看一下源码

    public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    
    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 内部维护了一个IntegerCache,
    -128 到 127 是byte的取值范围,如果在这个取值范围内,自动装箱就不会创建对象,而是从常量池中获取,如果超过了byte的取值返回就会再新创建对象;

  • 相关阅读:
    在python3中如何加载静态文件详版步骤
    django 过滤器总结
    通过虚拟环境创建并开始一个django
    关于django中模板的理解
    python 初学 正则表达式入门
    python 初学 错误类型以及编码规范
    获取地址的经纬度,根据经纬度反查地址
    mybatisz中一个可以替代between..and 的技巧
    linux指令和文件系统
    auto.js入门笔记
  • 原文地址:https://www.cnblogs.com/Godfunc/p/9195533.html
Copyright © 2011-2022 走看看