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这个对象型的数,还能自动增加
}
}
}
在幕后JVM已经自动执行了转换,同理Boolean和boolean之间也可以,自动拆箱装箱。但是,Integer和int毕竟还是有着不同的。看下面例子:
public class Test2 {
public static void main(String[] args) {
Integer i1 = 256;
Integer i2 =
256;
if (i1 = = i2)
System.out.println("相等!");
else
System.out.println("不相等!");
}
}
结果输出的是“不相等!”,两个对象比较,它们在内存中开辟的是两个地址怎么能相等呢?
警告:你可千万不能依赖这个结果,请把i1和i2的值,改成100。(请看Test3.java)看看什么结果,令人惊讶的是改了个数,居然输出了“相等!”。
这是因为JVM可以选择要尝试这段代码的最佳优化,并对两个Integer对象使用一个实例,这样的话“= =”就会返回true了。在自动装箱时对于值从–128到127之间的值,使用一个实例。上述例子打包下载
这种装箱与拆箱机制对,程序流程控制语句,也有很大影响:
public class Test4 {
public static void main(String[] args) {
Boolean arriving = true;
Integer peopleInRoom =
0;
int maxCapacity = 100;
while (peopleInRoom <
maxCapacity) {
if (arriving) {
System.out.printf("很高兴见到你.%d号先生\n",peopleInRoom);
peopleInRoom++;}
else {
peopleInRoom--;
}
}}}
另外一个从unboxing获得好处的语句是switch。在jdk5.0之前的JVM,switch接受int、short、character或者byte值,而在unboxing的操作中,你现在也可以为它赋予新引入的enum之外的Integer,Short,Char以及Byte值。Enum的值,我们在后面的教程会详细讲述。上述例子打包下载 |