装箱/拆箱机制

Integerint的包装类就是,从 Java 5 开始引入了自动装箱/拆箱机制,使得二者可以相互转换。

Java 为每个原始类型提供了包装类型:

原始类型 包装类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
public class AutoUnboxingTest {
    public static void main(String[] args) {
        int a = 1;
        Integer b = a;                      // int 类型的1自动装箱成 Integer 类型
        Integer c = new Integer(1);

        System.out.println(b == a);         // true -> b自动拆箱成 int 类型再和c比较
        System.out.println(c == b);         // false-> 两个引用没有指向同一对象
    }
}

装箱本质 Integer.valueOf()

先看个例题:

public class Test01 {
    public static void main(String[] args) {
        Integer i1 = 100, i2 = 100, i3 = 150, i4 = 150;

        System.out.println(i1 == i2);    // true
        System.out.println(i3 == i4);    // false
    }
}

i1、i2、i3、i4都是Integer对象引用,==比较的是引用而不是值

当我们给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,下面我们来看看 valueOf 方法

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

IntegerCacheInteger的内部类

/**
 * Cache to support the object identity semantics of autoboxing for values between
 * -128 and 127 (inclusive) as required by JLS.
 *
 * The cache is initialized on first usage.  The size of the cache
 * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
 * During VM initialization, java.lang.Integer.IntegerCache.high property
 * may be set and saved in the private system properties in the
 * sun.misc.VM class.
 */

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

从上面可看出,在范围 -128 ≤ i ≤127 之内的数值不会使用new创建新的Integer对象,直接引用常量池中的Integer对象;而超出这个范围将使用new创建新的Integer对象


YOLO