There are several principles for Java rewriting the hashCode() method:
1. If two objects are compared using the equals() method and return true (that is, equal), then the hashCode() returned by the two comparison objects must be equal. ((objB));
(() == ());
If (objB) is true, then ==() must also be true.
2. Call the hashCode() method of the same object multiple times. If the variable used in the equals() method has no change, the same hashCode value must be returned. User user = new User();
(10);
int hash1 = ();
int hash2 = ();
(11);
int hash3 = ();
If the User's equals() method uses age calculation, hash1 and hash2, the values of age are both 10 and have not been modified, then hash1 and hash2 are equal. Before calculating hash3, the age value is modified to 11, so the value of hash3 can be different from the previous hash1 and hash2, or can be equal.
3. Returning an object with equal hashCode is not necessarily equals(), which means that there is a hash value collision between different objects. Note that a good hash algorithm should allow different objects to have different hash values, which will improve the performance of hashing.
Rewrite method
Generally speaking, if we rewrite the equals() method of the class, it is best to rewrite the hashCode() method, and the member variables used in the equals() method also need to be calculated in hashCode().
The value returned by hashCode() is very important for the performance of structures that use hash storage (such as HashTable, HashSet, HashMap). It is best to override the hashCode() method to make different objects (that is, use equals() to vary) and return the values of different hashCodes.
Effective Java authors recommend using algorithms based on hash codes of 17 and 31, such as @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != ()) return false;
User user = (User) o;
if (!()) return false;
return age == ;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + ();
result = 31 * result + age;
return result;
}
The newly added Objects class in Java 7 provides a general method for calculating hashCode, which can easily implement hashCode@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != ()) return false;
User user = (User) o;
return (name, ) &&
(age, );
}
@Override
public int hashCode() {
return (name,age);
}