Blueherb In solitude, where we are least alone 王佳鑫

Integer 比较 == 要慎用

Integer 是包装类 ,在使用的时候会拆箱。Integer.valueOf

点击查看代码
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
源码中会根据IntegerCache缓存,判断是从缓存中获取 还是直接new Integer(); 如果是从缓存中获取,则 == 为true ,否则 new Integer() 为false。
点击查看代码
// The cache is initialized on first usage.  The size of the cache-----在第一次使用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;
            // jvm 启动时配置
            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;

            // 值从-128 开始 对应 k=0,以此类推
            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() {}
    }
posted @ 2022-06-27 16:54  阿呆学习之路  阅读(19)  评论(0编辑  收藏  举报