0
点赞
收藏
分享

微信扫一扫

java128陷阱

快乐小码农 2022-01-15 阅读 26

我们先看Integer中的源码

    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,在(-128,127]之间只有固定的256个值,所以为了避免多次创建对象,我们事先就创建好一个大小为256的Integer数组SMALL_VALUES,所以如果值在这个范围内,就可以直接返回我们事先创建好的对象就可以了。

public static void main(String[] args) {
		// TODO Auto-generated method stub
		Integer a = 127;
		Integer b = 127;
		Integer c = 128;
		Integer d = 128;
 
		System.out.println(a==b);
		System.out.println(c==d);
	}

在这里插入图片描述
也就有了如此结果

举报

相关推荐

128陷阱

Java核心卷——128陷阱

Java包装类及128陷阱

简述128陷阱

实例+源码 = 看破128陷阱

0 条评论