拆箱与装箱
在Java中,每个基本数据类型都有对应的一个引用类型,其之间的相互转换就被称为拆箱装箱。
基本数据类型 | 引用类型 |
---|---|
int(4字节) | Integer |
byte(1字节) | Byte |
short(2字节) | Short |
long(8字节) | Long |
float(4字节) | Float |
double(8字节) | Double |
char(2字节) | Character |
boolean | Boolean |
在装箱的过程中,例如int方法通过Integer的valueOf(int)转换,在拆箱时,Integer调用intValue转换为int类型。
要注意的地方
public class Main {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1==i2); // true
System.out.println(i3==i4); // false
}
}
产生上述结果的原因是,Integer的valueOf方法会缓存值在[-128,127]之间的对象引用,因此i1和i2指向的是同一个地址。这一点,Short,Byte,Character,Long都是类似的。而Double和Float则不然,换言之,它们会产生两个false的结果。而Boolean和bool的==含义一致。
下面的例子包含更多的情况:
public class Main {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
Long h = 2L;
System.out.println(c==d); // true
System.out.println(e==f); // false
System.out.println(c==(a+b)); // true
System.out.println(c.equals(a+b)); // true
System.out.println(g==(a+b)); // true
System.out.println(g.equals(a+b)); // false
System.out.println(g.equals(a+h)); // true
}
}
第四个判定,a+b先分别拆箱后相加,得到的和再装箱为Integer(由equals触发),与c数值和类型皆相等。第五个例子,a+b拆箱后求和为int,==只比较值。第六个例子,a+b拆箱装箱后是Integer而不是Long,类型不一致。