关于java自动装箱和自动拆箱


自动装箱和拆箱是一个老生常谈的问题了,今天我们谈一下我对这两个概念的理解。

一、自动装箱

java中一共有八种基本类型的数据,对于这些基本类型的数据都有一个对应的包装器类型。比如int——Integer等;

在javaSE5之前,如果需要对实现一个Integer对象必须如下:

Integer a = new Integer(10);

从JavaSE5开始就有了自动装箱的特性,如下:

//装箱
Integer i = 10;
Integer i
= Integer.valueOf(10);
//拆箱
int n = i;

那么上面的装箱和拆箱是如何实现的呢?

装箱的时候会调用Integer.vlaueOf方法,拆箱的时候会自动调用intValue方法。

那么什么时候装箱和拆箱呢?

1、对象初始化时候装箱。如:Integer i = 10;

2、使用表达式的时候拆箱。如:i+i

3、基本类型赋值时候拆箱。如:int a = i;

4、使用equals方法时候装箱。如:i.equals(表达式)。

猜一下下面的结果:

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));
    System.out.println(c.equals(a+b));
    System.out.println(g==(a+b));
    //a+b中a和b都是Integer类型,会先触发自动拆箱,变成int类型。然后触发自动装箱,变成Integer类型。类型不一样false
    System.out.println(g.equals(a+b));
    System.out.println(g.equals(a+h));

结果:

true
false
true
true
true
false
true