在1.5以前
Integer a = 1;
这样写是不对的,应该写成
Integer a1 = new Integer(1);
但是
Integer a = 1;
Integer a1 = new Integer(1);
执行
System.err.println("a==a1: "+ (a==a1));
System.err.println("a.equals(a1): "+ (a.equals(a1)));
第一个是错的,第二个对的
还有很多坑:
public void text3() {
Integer a = 1;
Integer a1 = new Integer(1);
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 432;
Integer f = 432;
Long g = 3L;
System.err.println("a==a1: "+ (a==a1));
System.err.println("a.equals(a1): "+ (a.equals(a1)));
System.err.println("==============");
System.err.println("c==d : "+(c==d));
System.err.println("c.equals(d) : "+(c.equals(d)));
System.err.println("e==f : "+(e==f));
System.err.println("e.equals(f) : "+(e.equals(f)));
System.err.println("==============");
System.err.println("c==(a+b): "+(c==(a+b)));
System.err.println("c.equals(a+b) : "+c.equals(a+b));
System.err.println("g==(a+b) : "+(g==(a+b)));
System.err.println("g.equals(a+b): "+g.equals(a+b));
}
结果有点颠覆俺的认知,
a==a1: false
a.equals(a1): true
==============
c==d : true
c.equals(d) : true
e==f : false //这里111==111,321却!=321,各种数字试过,结果很奇葩
e.equals(f) : true
==============
c==(a+b): true
c.equals(a+b) : true
g==(a+b) : true
g.equals(a+b): false
==运算符在不遇到算数运算的情况下,不会自动拆箱,equals方法不处理数据转型的关系,
慎用自动装箱和拆箱啊。、、、、