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!