The hashcode in the object class has a very close logical relationship with the equals function. Of course, this logical relationship is granted by people. Before the two functions are overwritten, hashcode returns the address, and equals compares the addresses of the two application objects. That is to say, if two objects are equals, The hashcode value should be the same.
The comparison of object content is the true purpose of designing equals (). the Java language has the following requirements for equals (), which must be followed. Otherwise, you should not waste time: Symmetry: If X. Equals (y) returns "true", then Y. Equals (x) should return "true ". Reflex: X. Equals (x) must return "true ". Analogy: If X. equals (y) returns "true", and Y. equals (z) returns "true", then z. equals (x) should also return "true ". There is also consistency: If X. equals (y) returns "true", as long as the content of X and Y remains unchanged, No matter you repeat X. "True" is returned for the number of equals (y) times ". In any case, X. Equals (null) always returns "false"; X. Equals (and X objects of different types) always returns "false ".
The relationship between the return value of hashcode () and equals () is as follows: if X. Equals (y) returns "true", the hashcode () of X and Y must be equal. If X. Equals (y) returns "false", the hashcode () of X and Y may be equal or different. Several hashcode conventions defined in the object class are as follows:
1. In the same application, the hashcode function of an object must return the same integer no matter how many times the equals function is called.
2. If the two objects call the equals function to be equal, the hashcode function will certainly return the same integer.
3. If the two objects call the equals function, different integers are not required to be returned to call the hashcode function.
When rewriting equals and hashcode functions, we must abide by the above three conventions. While rewriting equals, we must also rewrite the implementation of hashcode to ensure correct results.