1.什么是装箱?什么是拆箱?
装箱就是把值类型转变为引用类型Integeri=10;
拆箱就是把引用类型转变为值类型inti=newInteger(10)。
实践程序:
public class Test1{
public static void main (String [] args){ //装箱
int i=0;
Integer integer = i;
//i这么一个基本类型的数,可以赋值给Integer型的变量
//简单的拆箱
int j = integer;//integer这种原始类型的数,也能赋值给j这个原始类型的变量 Integer counter = 1;//装箱
int counter2 = counter; //拆箱
while (counter<100){
System.out.println("计数"+counter++);//看啊,counter这个对象型的数, 还能自动增加
}
}
}
简单一点说:装箱就是 自动将基本数据类型转换为包装器类型;
拆箱就是 自动将包装器类型转换为基本数据类型。
以下是基本数据类型对应的包装器类型:
int(4字节)Integer
byte(1字节)Byte
short(2字节)Short
long(8字节)Long
float(4字节)Float
double(8字节)Double
char(2字节)Character
boolean(未定)Boolean
2.装箱拆箱如何实现?
以Interger类为例,下面看一段代码:
1 public class Main {
2 public static void main(String[] args) {
3 Integer i = 10;
4 int n = i;
5 }
6 }
反编译class文件之后得到如下内容:
从反编译得到的字节码内容可以看出,在装箱的时候自动调用的是Integer的valueOf(int)方法。而在拆箱的时候自动调用的是Integer的intValue方法。
其他的也类似,比如Double、Character。
因此可以用一句话总结装箱和拆箱的实现过程:
装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。(xxx代表对应的基本数据类型)。