关于Integer和int的拆箱和装箱
什么是拆箱和装箱
Integer称为包装类,所以自动装箱自然是相对于int来说,转化为Integer。相反,拆箱就是Integer转int。
拆箱和装箱的分类
隐式/自动
装箱
定义一个Integer对象,赋一个int值,会自动转化为Integer
Integer boxedInt = 10;
拆箱
把刚刚定义的Integer直接赋值给int,会自动转化为int
int autoUnboxedInt = boxedInt;
显式
装箱
先定义一个int变量,再调用integer中的静态方法转为Integer
int primitiveInt = 5;
Integer boxedInt = Integer.valueOf(primitiveInt); // 显式装箱
拆箱
先定义一个Integer变量,再调用内置方法转为int
Integer boxedInt = 10; // 由于存在自动装箱,这里实际上创建了一个Integer对象
int primitiveInt = boxedInt.intValue(); // 显式拆箱