Consider the following Java code:
Object a = new Integer(2);
Object b = new Integer(2);
System.out.println(a.equals(b));
Object x = new Object();
Object y = new Object();
System.out.println(x.equals(y));
The first print statement prints true
and the second false
.
If this is an intentional behavior, how this helps programming in Java?
If this is not an intentional behavior, is this a defect in Java?
I'm going to answer your question with reservations, but you should know that you are hurting yourself if the intent of the question was to get you to learn and your solution was to ask StackOverflow. That aside...
This behavior is intentional.
The default equals()
method on java.lang.Object
compares memory addresses, which means that all objects are different from each other (only two references to the same object will return true
).
java.lang.Integer
overrides this to compare the value of the Integer
s, so two different Integer
s both representing the number two compare equal. If you used ==
instead, you would get false
for both cases.
Standard practice in Java is to override the equals
method to return true
for objects which have the same logical value, even if they were created at different times (or even with different parameters). It's not very useful to have objects representing numbers if you don't have a way to ask, "do these two things represent the same value?".
Incidentally, and this is a tangent here, Java actually keeps a cache of Integer
objects for small values. So sometimes you may get two Integer
objects where even the ==
operator will return true
, despite you getting them from two different sources. You can even get code that behaves differently for larger integers than it does for smaller, without having it look at the integral values!
This is intended behaviour.
Object.equals()
considers the object identity (i.e. an object is only equal to itself), which is the only thing you can do for generic objects.
Integer
overrides the method to depend on the integer value, since two Integer objects with the same value are logically equal. Many other classes also override equals()
since it's a core mechanism of the standard API and a lot of functionaliy e.g. in the collections framework depends on it.
Why do are you puzzled by the behaviour anyway? Most people are only confused by the ==
operator not behaving like that (it works like Object.equals()
).
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