Integer的常量池,自动拆装箱源码分析

首先我们来看一下常量池的概念,当-128<= i <=127会直接从常量池中取,不会新new对象(这也是很多面试题中Integer128,和127比较的区别)下面是Integer维护常量池的源码。

	static final int low = -128;
    static final int high;
    static final Integer cache[];

	//静态代码块,类一加载就会被执行
    static {
        // high value may be configured by property
        //在这里将最大值设置成127
        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++)
        	//将-128到127装在数组中
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

通过上面的源码我们可以看出Integer类在初始化的时候,会维护一个常量池(就是一个数组),装着-128到127这255个数。

接着我们来看下面这两句代码

		Integer x = 10;
		x += 20;

这两句代码做了哪些事情?

首先第一句 Integer x = 10
当java进行编译的时候,会变成 Integer x = Integer.valueOf(10);
也就是说这两句代码是等价的,这就是自动装箱。我们点进源码看看

//IntegerCache.low = -128
//IntegerCache.high = 127

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

我们会发现当127>= i >=-128时会从常量池中直接获取,否则会新new一个对象,这就是自动装箱

第二句x += 20;等价于 x = Integer.valueOf(x.intValue() + 20);
其中intValue()方法就是自动拆箱的方法,这里我们看看源码
可以看到返回的是value,这是Integer类中的一个int类型的字段。
也就是说x.intValue() 其实返回的是一个int类型的数字。

private final int value;

public int intValue() {
    return value;
}

你可能感兴趣的:(java基础)