[Java Interview] "Have you rewritten hashCode() and equals()? Why do you have to rewrite the hashCode method when rewriting equals?"

insert image description here

The Java specification stipulates that if two objects are compared with equals and the result is true, then the return values ​​of the hashCode methods of the two objects must be equal.
It does not stipulate that two objects are not equal, that is, equals returns false, and the return value of the hashCode method must not be equal.

So why do you have to rewrite hashCode when rewriting equals? Because you must abide by the Java specification!

We have rewritten equals to judge whether two objects are equal according to the content of the object. If hashCode is not rewritten, it is a local method called. This hashCode local method (that is, the hashCode method in the Object class) can only guarantee The hashCode return value of the same object is equal , but it cannot guarantee that the hashCode return values ​​of two objects with equal content are equal, so the hashCode method needs to be rewritten to ensure that the hashCode return values ​​of two objects with equals equals are equal.

Supplement: Some people say that the hashCode method in the Object class returns the address of the object in memory, which is also a wrong statement. See this article for details: Does the hashCode method in Object return the address of the object in memory? No!

insert image description here

Guess you like

Origin blog.csdn.net/huhuhutony/article/details/120815494