Reputation: 6748
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
?
Upvotes: 1
Views: 5529
Reputation: 306
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);
Upvotes: 0
Reputation: 48258
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.
Upvotes: 3
Reputation: 6748
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);
Upvotes: 5