I'm going to answer your question with reservations, but you should know that you are hurting yourself if the purpose of the question is for you to learn, and your solution was to ask StackOverflow. That aside ...
This behavior is intentional.
The default equals() method java.lang.Object compares memory addresses, which means that all objects are different from each other (only two references to the same object return true ).
java.lang.Integer overrides this to compare the value of Integer s, so two different Integer representing the number two are compared equal. If you used == instead, you will get false for both cases.
A standard practice in Java is to override the equals method to return true for objects with the same boolean value, even if they were created at different times (or even with different parameters). It is not very useful to have objects representing numbers if you have no opportunity to ask: "Do these two things represent the same meaning?"
By the way, and this is tangent here, Java actually stores the cache of Integer objects for small values. Therefore, sometimes you can get two Integer objects, where even the == operator will return true , despite the fact that you get them from two different sources. You can even get code that behaves differently for large integers than for a smaller size, excluding integral values!
Borealid
source share