简体   繁体   English

为什么当相等值时Long equals返回false?

[英]Why does Long equals return false when are the same value?

Running the following code I expect true as result, but the output I get is false . 运行以下代码,我希望结果为true ,但得到的输出为false

Long value = new Long(0);
System.out.println(value.equals(0));

Why does the equals comparison of Long return false ? 为什么Longequals比较返回false

Long.equals return true only if the argument is also a Long . 仅当参数也是Long Long.equals返回true

The javadoc says: Javadoc说:

Compares this object to the specified object. 将此对象与指定对象进行比较。 The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object . 当且仅当参数不为null且是一个Long对象,并且包含与此对象相同的long值时,结果才为true。

In fact the following code gets true as output. 事实上,以下代码获取true的输出。

Long value = new Long(0);
System.out.println(value.equals(new Long(0)));
System.out.println(value.equals((long) 0));
System.out.println(value.equals(0L);

looking inside in the implemented compare method you will find the critical criteria: 在已实现的compare方法中查看,您将发现关键条件:

if (obj instanceof Long) 



public boolean equals(Object obj) {
    if (obj instanceof Long) {
        return value == ((Long)obj).longValue();
    }
    return false;
}

so passing any other numeric type will return false, even if the hold the same value... 因此,即使保持相同的值,传递任何其他数字类型也将返回false。

Integer i = 0;

and

Long l = 0L;

are not the same in that context. 在那种情况下是不一样的。

You compared an Long with an int! 您将Long与int进行了比较!
the .equals method also is checking the type of the Variable. .equals方法也正在检查变量的类型。
Here is a code to campare an int with an long: 这是一个将int长整型的代码:

int i = 0;
long l = 0L;

//v1
System.out.println(i == l);
//v2
Long li = new Long(i);
Long ll = new Long(l);
System.out.println(li.eqauls(ll));
//v3
System.out.println(((long)i) == l);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM