public static void main(String[] args){
Integer a=30000;
Integer b=30000;
Integer c=30;
Integer d=30;
System.out.println(a.equals(b));
System.out.println(a==b);
System.out.println(a==30000);
System.out.println(d.equals(c));
System.out.println(d==c);
System.out.println(c==30);
}[@more@]
运行结果为:
true
false
true
true
true
true
打印结果说明-128 到 127的数值,怎么比较都一样,其它的只有equals时才相等.
Java自动装箱是对于从 -128 到 127 之间的信息值,它们在被装箱为对象数据后会在内存中被重用,也就是对于相同的值,返回的是同一个对象.直接与数值比较时,大概是拆箱比较了,就跟 int的比较一样了,所以还是相等的.
了解了上面的,在java中,我们以后要是再判断 变量 Integer a=1000时,就会 a==1000而不是equals,或者强制转化为 字符串,”1000”.equals(a.toString())这样难懂的代码了.当然了还必须检查是否为NULL,为空时还是会报错的.
所以判断Integer还是用equals
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/25261409/viewspace-1051282/
,如需转载,请注明出处,否则将追究法律责任。