Running the following code I expect true
as result, but the output I get is false
.
Long value = new Long(0);
System.out.println(value.equals(0));
Why does the equals
comparison of Long
return false
?
Long.equals
return true
only if the argument is also a Long
.
The javadoc says:
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 .
In fact the following code gets true
as output.
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:
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...
Integer i = 0;
and
Long l = 0L;
are not the same in that context.
You compared an Long with an int!
the .equals method also is checking the type of the Variable.
Here is a code to campare an int with an long:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.