The rewritten equals method in java

  java, question

It is to compare whether two objects have the same category of attributes. When ture, why do they have the same Hash code, that is, the same memory address?
The comparison address is = = isn’t it?

First, hashCode has nothing to do with the memory address.

Equals is defined as returning true when two objects are equivalent, otherwise returning false. The implementation of equals usually compares all member variables in two objects. If some member variables are containers or objects, it is also necessary to judge whether the containers or objects in the two objects are equal. Generally speaking, this is a relatively expensive operation.

The function of hashCode is to determine the storage location in hashMap and hashSet and to complete initial screening (such as de-duplication) in large-scale equivalence comparison. Its definition is that when two objects are equivalent, there must be equal hashCOde, and when they are not equivalent, there must be different hashCode as much as possible. When removing weight, if there is no hashCode, then n(n-1)/2 times of equals are required, while if there is hashCode, only n times of hashCode and n(n-1)/2 times of int equality judgment are required, and then equals comparison is performed when hashCode is equal. The efficiency will be much higher.

The generation method of hashCode can be determined by itself, which can be the sum of all variables processed into numbers, or md5 converted into int after all variables are merged. It can also be the result of processing some of the variables. In short, hashCode’s realization principle is to ensure that the two objects whose equals are true are the same, so that the objects whose equals are false are as different as possible, and at the same time, it is also to improve the execution efficiency of hashCode itself.