天天看点

装箱和拆箱,自动装箱和自动拆箱装箱和拆箱,自动装箱和自动拆箱

装箱和拆箱,自动装箱和自动拆箱

以Integer的创建为例。

装箱和拆箱

装箱:把基本数据类型转换成包装类对象(int—>Integer)

Integer num1=new Integer(17);
           

拆箱:把一个包装类的对象,转换成基本类型的变量(Integer—>int)

int num2=num1.intValue();
           

自动装箱和自动拆箱

自动装箱:

Integer num3=17;
           

自动拆箱:

int num4=num3;
           

自动装箱和拆箱操作又是一个“语法糖”,只是编译器级别的新特性。 在底层依然是手动的拆箱和装箱。

装箱的具体实现

Integer num=new Integer("132");
//调用了构造器,在构造其中可以把String转化为Integer的parseInt()
System.out.println(num);
//Integer num6="18";没有调用构造器所以不可以
           

integer的构造方法:

public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }
           

可以看到里面的parseInt方法就是将Integer(“132”)里的字符串转换为int类型的数的主要方法。