public static void main(String[] args) {
Long lo = new Long(1);
Integer a = new Integer(1);
int aa = 1;
System.out.println(lo.equals(a)); //false
System.out.println(lo==aa); //true
System.out.println(lo==a); //编译错误
}
为什么
System.out.println(lo==aa)
会输出true呢?
而
System.out.println(lo.equals(a))
则输出false呢?
想听听前辈们的意见
------解决方案--------------------
System.out.println(lo==aa):因为lo先自动拆箱成long类型,值为1,而aa的值也是1,因此true。
System.out.println(lo.equals(a)):因为在Long类的JDK实现中:
boolean equals(Object obj)
{
if(!obj instanceof Long) return false;
}
也就是说,只要传入的参数不是一个Long类型,都是返回false。
------解决方案--------------------
正解。
再看看生成的class反编译后的代码就清楚了
public static void main(String[] args)
{
Long lo = new Long(1L);
Integer a = new Integer(1);
int aa = 1;
System.out.println(lo.equals(a));
System.out.println(lo.longValue() == aa);
}