装箱与拆箱定义:基本数据类型和包装类之间可以自动地相互转换
理解:装箱就是自动将基本数据类型转换为封装类型,拆箱就是自动将封装类型转换为基本数据类型。
类型封装器(包装类)
- 自动装箱时编译器调用
valueOf
将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue()
,doubleValue()
等这类的方法将对象转换成原始类型值。 - 自动装箱是将
boolean
值转换成Boolean
对象,byte
值转换成Byte
对象,char
转换成Character
对象,float
值转换成Float
对象,int
转换成Integer
,long
转换成Long
,short
转换成Short
,自动拆箱则是相反的操作。
何时发生
1 赋值时
这是最常见的一种情况,在Java 1.5
以前需要手动地进行转换才行,而现在所有的转换都是由编译器来完成
//before autoboxing
Integer iObject = Integer.valueOf(3);
Int iPrimitive = iObject.intValue()
//after java5
Integer iObject = 3; //autobxing - primitive to wrapper conversion
int iPrimitive = iObject; //unboxing - object to primitive conversion
2 方法调用时
这是另一个常用的情况,当在方法调用时,可以传入原始数据值或者对象,同样编译器会帮我们进行转换。
public static Integer show(Integer iParam){
System.out.println("autoboxing example - method invocation i: " + iParam);
return iParam;
}
//autoboxing and unboxing in method invocation
show(3); //autoboxing
int result = show(3); //unboxing because return type of method is Integer
show
方法接受Integer
对象作为参数,当调用show(3)
时,会将int
值转换成对应的Integer
对象,这就是所谓的自动装箱,show
方法返回Integer
对象,而int result = show(3);
中result
为int
类型,所以这时候发生自动拆箱操作,将show
方法的返回的Integer
对象转换成int
值。