先看段代码:
public static void main(String[] arg){
Integer a=300000;
Integer b=300000;
Integer c=30;
Integer d=30;
System.out.println(a.equals(b));
System.out.println(a==b); //false
System.out.println(a==300000);
System.out.println(d.equals(c));
System.out.println(d==c);
System.out.println(d==30);
}
public static void main(String[] arg){ Integer a=300000; Integer b=300000; Integer c=30; Integer d=30; System.out.println(a.equals(b)); System.out.println(a==b); //false System.out.println(a==300000); System.out.println(d.equals(c)); System.out.println(d==c); System.out.println(d==30); }
打印结果说明-128 到 127的数值,怎么比较都一样,其它的只有equals时才相等.
Java自动装箱是对于从 -128 到 127 之间的信息值,它们在被装箱为对象数据后会在内存中被重用,也就是对于相同的值,返回的是同一个对象.
直接与数值比较时,大概是拆箱比较了,就跟 int的比较一样了,所以还是相等的.
了解了上面的,在java中,我们以后要是再判断 变量 Integer a=1000时,就会 a==1000而不是equals,或者强制转化为 字符串,”1000”.equals(a.toString())这样难懂的代码了.当然了还必须检查是否为NULL,为空时还是会报错的.