128陷阱
先看如下代码,发现同是==判断 a=10时与A=1000时竟然出现两种结果:
public static void main(String[] args) {
Integer a=10;
Integer b=10;
Integer c=new Integer(10);
System.out.println(a==b);//true
System.out.println(a==c);//false
System.out.println(a.equals(b));//true
System.out.println(a.equals(c));//true
System.out.println("———————————————");
Integer A=1000;
Integer B=1000;
Integer C=new Integer(1000);
System.out.println(A==B);//false//注意这个竟然是false!!
System.out.println(A==C);//false
System.out.println(A.equals(B));//true
System.out.println(A.equals(C));//true
}
因为 有时需要将基本类型转换成对象,所以每个基本类型都又对应的类——这样的类被称为包装器。
例如:Integer类对应基本类型int
1.对象包装器是不可变的,一旦构造,不允许更改其中的值。
2.对象包装器是final,不允许定义其子类。
所以在用Integer时会涉及到自动拆箱装箱
自动装箱规范要求-128~127之间的short和int被包装到固定对象中
超出这个范围,哪怕自动装箱也不是同一个
所以这个说明A、B的装箱是两个,所以指向不同、所以==为false
Integer A=1000;
Integer B=1000;