装箱:自动将基本数据类型转换为包装器类型;
拆箱:自动将包装器类型转换为基本数据类型。
拿 int 和 Integer 举例:
Integer i = 77;
//Integer i = 77; 就是一个装箱的过程,相当于Integer i = Integer.valueOf(77);
int i2 = i;
//int i2 = i; 就是一个拆箱的过程,相当于 int i2 = i.intValue();
需要注意的几点是:
- -128 ~ 127 的整数会进行缓存,因此在定义两个以上对象时,若值相等且范围在 -128 ~ 127 之间,则 Java就会返回相同的地址,若超过这个返回,就会新建一个对象。byte,short,int,long都是如此,不过 byte 就是它本身的范围罢了。
- '\u0000' ~ '\u007f' 的字符型。
- 布尔类型的值都会缓存。
- 浮点型都是返回新的对象。
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b); // true
System.out.println(c == d); // false
Character a = '\u007f';
Character b = '\u007f';
Character c = '\u0080';
Character d = '\u0080';
System.out.println(a == b); // true
System.out.println(c == d); // false
Boolean a = true;
Boolean b = true;
Boolean c = false;
Boolean d = false;
System.out.println(a == b); // true
System.out.println(c == d); // true
Double a = 127.0;
Double b = 127.0;
Double c = 128.0;
Double d = 128.0;
System.out.println(a == b); // false
System.out.println(c == d); // false
相关方法:a.equals(b)、a == b、Objects.equals(a, b):
- a.equals(b) 不比较对象的地址,只要 a,b 类型相同并且值相等,该方法就返回真,但注意 a 不能为空。
- a == b 在 a,b 为基本数据类型时,比较的是数据的大小;在 a,b 为引用类型时,比较的是引用类型中存放的地址。
- Objects.equals(a, b) 和 a.equals(b) 类似,不同的是 a 为空时也可以比较,都为空返回真,一个为空返回假。使用时需要导入 java.util.Objects 包。
Integer a = 128;
Integer b = 128;
Integer c = null;
Integer d = null;
System.out.println(a.equals(b)); // true
System.out.println(a == b); // false
System.out.println(Objects.equals(a, b)); // true
//System.out.println(c.equals(d)); // java.lang.NullPointerException
System.out.println(c == d); // true
System.out.println(Objects.equals(c, d)); // true