Let's first consider the following expressions in Java.
Integer temp = new Integer(1);
System.out.println(temp.equals(1));
if(temp.equals(1))
{
System.out.println("The if block executed.");
}
These all statements work just fine. There is no question about it. The expression temp.equals(1)
is evaluated to true
as expected and the only statement within the if
block is executed consequently.
Now, when I change the data type from Integer
to Long
, the statement temp1.equals(1)
is unexpectedly evaluated to false
as follows.
Long temp1 = new Long(1);
System.out.println(temp1.equals(1));
if(temp1.equals(1))
{
System.out.println("The if block executed.");
}
These are the equivalent statements to those mentioned in the preceding snippet just the data type has been changed and they behave exactly opposite.
The expression temp1.equals(1)
is evaluated to false
and consequently, the only statement within the if
block is not executed which the reverse of the preceding statements. How?
You're comparing a Long
to an int
. The javadoc for java.lang.Long#equals
says that the equals
method
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.
Instead try System.out.println(new Long(1).equals(1L));
Now that you're comparing a Long
to a Long
instead of a Long
to an Integer
, it will print true
.
The reason you can do that comparison is because of autoboxing in Java.
The actual method you are calling is this:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Long.html#equals(java.lang.Object)
which is comparing your Long object to some other Object, not to an actual primitive int.
What happens when you call the method is that your primitive integer(1)
is being autoboxed into an Object(Integer)
so then you are effectively calling:
new Long(1).equals(new Integer(1));
which is why it fails.
This is why if you call
new Long(1).equals(1L)
this would work, because Java will autobox the 1L
(primitive long
, not int
) into a Long
object, not an Integer
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With