Java关于Integer自动装箱

跟着金旭亮老师的ppt重新学习java基础,看到这个例子决定自己去理解一下

之前也知道Integer的两个数字超过127,再比较,结果会是false,但是不明所以,现在回头重新自己看一下

public class IntegerOverflow {
    public static void main(String[] args) {
        Integer value1 = 100;
        Integer value2 = 100;

        System.out.println(value1 == value2); // true

        Integer value3 = 129;
        Integer value4 = 129;
        System.out.println(value3 == value4); // false
    }
}
1、找到该类的 .class 文件,丢进XJad(java反编译工具):

class文件在 项目位置/out/production/项目名/包名/类名.class

public class IntegerOverflow
{

	public IntegerOverflow()
	{
	}

	public static void main(String args[])
	{
		Integer value1 = Integer.valueOf(100);
		Integer value2 = Integer.valueOf(100);
		System.out.println(value1 == value2);
		Integer value3 = Integer.valueOf(127);
		Integer value4 = Integer.valueOf(127);
		System.out.println(value3 == value4);
	}
}

发现自动装箱时调用valueof来完成的

2、跟进valueof源码查看:

IDEA环境下,双击shift,搜索valueOf,找到java.lang.Inetger包里

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() {}
    }

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

static块里的代码主要是做了一个初始化,获取给定的high值,这样就有了low = -128,high = 127
cache为一个静态缓存数组,大小为128 +127 + 1 = 256,在类加载时就被创建完毕,只创建一次。
在for循环中初始化cache数组 ,cache[0] 为 -128 ,cache[255] 为127,也就是说类里面存了一个拥有-128 ~ 127之间的数,用的时候直接取,省去了创建新对象的内存开销。
接下来就是valueOf了,先判断了该参数 i 是否在[-128,127]范围内,如果是就直接取cache数组里面对应下标的数字返回,如果不是,则 return new Inetger(i)

3、真相大白

所以我们首段代码的value3和value4,虽然值都是129,但是超出了127,所以value3和value4其实是两个不同的对象,所以在==比较的时候,是不相同的。

你可能感兴趣的:(Java关于Integer自动装箱)