public static void main(String[] args) {
Integer num1 = 100;
Integer num2 = 100;
System.out.println(num1 == num2);
Integer num3 = 128;
Integer num4 = 128;
System.out.println(num3 == num4);
}
ture
false
解析
答案就在Integet的valueOf()方当中,如果我们的数值在-128-127之间的数值都存储在有一个catch数组当中,该数组相当于一个缓存,当我们在-128-127之间进行自动装箱的时候,我们就直接返回该值在内存当中的地址,所以在-128-127之间的数值用==进行比较是相等的。而不在这个区间的数,需要新开辟一个内存空间,所以不相等。
基本数据类型 == 比较值
引用数据类型 == 比较地址
用 equals() 判断,自动装箱 ,当我们在-128-127之间进行自动装箱的时候,我们就直接返回该值在内存当中的地址,所以在-128-127之间的数值用==进行比较是相等的。
而不在这个区间的数,需要新开辟一个内存空间,所以不相等。
public static void main(String[] args) {
int a = 10;
int b = 10;
Integer a1 = 10;
Integer b1 = 10;
Integer a2 = new Integer(10);
Integer b2 = new Integer(10);
System.out.println(a == b);
// T 基本数据类型 == 比较值
System.out.println(a1 == b1);
// T 128陷阱
System.out.println(a2 == b2);
// F 引用数据类型 == 比较地址
System.out.println(a1 == a);
// 用 == 判断,一个是int,一个是integer自动拆箱
System.out.println(a1.equals(a));
// 用 equals() 判断,自动装箱
System.out.println(a1 == a2);
System.out.println(a == a2);
// 用 == 判断,一个是int,一个是integer自动拆箱
}
自动装箱
1 public class Main {
2 public static void main(String[] args) {
3 //自动装箱
4 Integer total = 99;
5
6 //自定拆箱
7 int totalprim = total;
8 }
9 }
Integer类型是装箱
自动拆箱
把integer转换成int 就是拆箱