自动装箱和拆箱

588 阅读4分钟

1. 基本概念

自动拆箱和自动装箱是 JDK1.5以后才有的功能,也就是java当中众多的语法糖之一,它的执行是在编译期,会根据代码的语法,在生成class文件的时候,决定是否进行拆箱和装箱动作。

①、自动装箱

我们知道一般创建一个类的对象需要通过 new 关键字,比如:

Object obj = new Object();

但是实际上,对于 Integer 类,我们却可以直接这样使用:

Integer a = 128;

为什么可以这样,通过反编译工具,我们可以看到,生成的class文件是:

Integer a = Integer.valueOf(128);

如果函数的参数是一个对象,那么将int类型的数值a传入,会自动调用Integer.valueOf(a)转换成对象

Integer a = 1;
int b = 1;
a.equals(b); // true

反编译得

Integer a = 1;
int b = 1;
a.equals(Integer.valueOf(b)); // true

其中equals方法为:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

②、自动拆箱

我们将 Integer 类表示的数据赋值给基本数据类型int,就执行了自动拆箱。

 Integer a = new Integer(128);
 int m = a;

反编译生成的class文件:

 Integer a = new Integer(128);
 int m = a.intValue();

简单来讲:自动装箱就是Integer.valueOf(int i);自动拆箱就是 i.intValue();

2. 缓存池

①、Integer缓存池

new Integer(123) 与 Integer.valueOf(123) 的区别在于:
new Integer(123) 每次都会新建一个对象;
Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。
Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y);    // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k);   // true

valueOf() 方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。

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

在 Java 8 中,Integer 缓存池的大小默认为 -128~127。

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

static {
    // high value may be configured by property
    /*
    在 jdk 1.8 所有的数值类缓冲池中,Integer 的缓冲池 IntegerCache 很特殊,
    这个缓冲池的下界是 - 128,上界默认是 127,但是这个上界是可调的,
    在启动 jvm 的时候,通过 -XX:AutoBoxCacheMax=<size> 来指定这个缓冲池的大小,
    该选项在 JVM 初始化的时候会设定一个名为 java.lang.IntegerCache.high 系统属性,
    然后 IntegerCache 初始化的时候就会读取该系统属性来决定上界。
    */
    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;
}

编译器会在自动装箱过程调用 valueOf() 方法,因此多个值相同且值在缓存池范围内的 Integer 实例使用自动装箱来创建,那么就会引用相同的对象。

Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true

②、其他基本数据类型包装器类缓存池

  • boolean values true and false
  • all byte values
  • short values between -128 and 127
  • int values between -128 and 127
  • char in the range \u0000 to \u007F

在使用这些基本类型对应的包装类型时,如果该数值范围在缓冲池范围内,就可以直接使用缓冲池中的对象。

为什么Double类的valueOf方法会采用与Integer类的valueOf方法不同的实现。很简单:在某个范围内的整型数值的个数是有限的,而浮点数却不是。

注意,Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。    Double、Float的valueOf方法的实现是类似的。

3. 实例

下面程序的输出结果是什么

public class Main {
    public static void main(String[] args) {
         
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
         
        System.out.println(c==d);
        System.out.println(e==f);
        
        // 算数运算触发自动拆箱
        System.out.println(c==(a+b));
        
        // a+b自动拆箱,得3;因为equals,3自动装箱:Integer.valueOf(3)
        System.out.println(c.equals(a+b));
        
        // 算数运算触发自动拆箱
        System.out.println(g==(a+b));
        
        // a+b自动拆箱,得3,还是int类型;因为equals,3自动装箱:Integer.valueOf(3);
        // 但是此时3是Integer对象,与Long对象不符,返回false
        System.out.println(g.equals(a+b));
        
        // a+h自动拆箱,得3,此时自动转换为long类型;因为equals,3自动装箱:Long.valueOf(3);
        System.out.println(g.equals(a+h));
    }
}
/*
true
false
true
true
true
false
true
 */

4. 最后

装箱操作会创建对象,频繁的装箱操作会造成不必要的内存消耗,影响性能。所以应该尽量避免装箱。

参考