gogoWebsite

Java override equals method and hashCode method

Updated to 17 days ago
What are the () method and hashCode() method?
  1. equals() and hashCode() are both methods in the Object class, the source of everything in Java;
  2. The equals method is used to compare whether two objects are the same. The implementation of the equals method in the Object class is to compare the reference address to determine whether the object is the same object. By overwriting this method, custom judgment rules can be implemented;
  3. hashCode is a method in which jdk calculates the hash code value of the object based on the address, string or number of the object.
2. Why do we need to rewrite the equals() method?
  1. The equals method in the Object class compares the reference addresses of two objects. Only when the reference address of the object points to the same address, do they think that the two addresses are equal, otherwise the two objects do not want to wait.
  2. If there are two objects, their properties are the same but their addresses are different, the results obtained by using equals() comparison are not equal, and what we need is that these two objects are equal, so the default equals() method does not meet our requirements. At this time, we need to rewrite the equals() method to meet our expected results.
  3. In Java's collection framework, the equals() method needs to be used to find objects. If the set stores a custom type and the equals() method is not overridden, the equals() method in the Object parent class will be called to compare according to the address, and there will often be error results. At this time, we should rewrite the equals() method according to business needs.
3. Why do you need to override the hashCode() method?
  1. The hashCode() method is used for fast storage of hash data. When the HashSet/HashMap/Hashtable class stores data, it is classified and stored according to the hashcode value of the stored object. Generally, it is first classified in the set based on the hashcode value, and judges whether the object is the same according to the equals() method.
  2. The HashMap object obtains the corresponding value based on its key hashCode.
  3. Generating a good hashCode value can improve the performance of HashSet searches. Poor hashCode value not only fails to improve performance, but may even cause errors. For example, returning constants in hashCode method will degrade the search efficiency of HashSet to the search efficiency of List collections; returning random numbers in hashCode method will make the search results unpredictable.
  4. A good hashCode generation method is to multiply the key attributes in the object with prime numbers and add products to obtain.
4. Why must the hashCode() method be rewrite after rewriting the equals() method in Java?
  1. In order to maintain the equals contract of the hashCode() method, the contract states that if two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must generate the same integer result; while the results returned by the two hashCode() are equal, and the equals() methods of the two objects are not necessarily equal.
  2. The HashMap object obtains the corresponding value based on its key hashCode.
  3. When overriding the equals() method of the parent class, the hashcode() method is also overridden to make the HashCode values ​​obtained by two equals objects also equal. In this way, when this object is used as a key in the Map class, the values ​​obtained by the two equals true objects are the same, which is more in line with reality.
5. Rewrite the equals() method:

Rewriting the equals method requires following Java rules, otherwise the encoding behavior will be difficult to guess:

  1. Reflexivity: For any object x, (x) returns true (it must be equal to it);
  2. Symmetry: For any object x and y, if (y) is true, then (x) is also true;
  3. Transitiveness: For any objects x, y, and z, if (y) is true and (z) is also true, then (z) is also true;
  4. Consistency: For any objects x and y, the first call of (y) is true, then the second, third, and nth calls of (y) are also true, the prerequisite is that x and y are not modified;
  5. For non-null reference x, (null) always returns false.

Rewrite the code as follows:


    @Override
    public boolean equals(Object o) {
        //Reflexive
        if (this == o) return true;
        //Any object is not equal to null, compare whether it is of the same type
        if (!(o instanceof Person)) return false;
        //Corresize type conversion
        Person person = (Person) o;
        //Compare property values
        return getId() == () &&
                (getName(), ()) &&
                (getSex(), ());
    }
6. Rewrite the hashCode() method:

The HashMap object obtains the corresponding value based on its key hashCode.
When overriding the equals method of the parent class, the hashcode method is also overridden so that the HashCodes obtained by two equals objects are also equal. In this way, when this object is used as a key in the Map class, the value obtained by the two equals true objects are the same, which is more realistic.

Rewriting the hashCode() method requires the hashCode() protocol:

  1. Consistency: During Java application execution, when the hashCode method is called multiple times on the same object, the same integer must be returned consistently, provided that the information used when comparing the object hashcode has not been modified.
  2. equals: If the two objects are equal according to the equals() method, then calling the hashCode() method on each of the two objects must generate the same integer result. Note: The equals() method mentioned here refers to the equals() method in the Object class that has not been rewritten by a subclass.
  3. Additional: If the two objects are not equal according to the equals() method, calling the hashCode method on either of the two objects does not necessarily generate different integer results. However, programmers should realize that generating different integer results for unequal objects can improve the performance of the hash table.

Rewrite the code as follows:


    @Override
    public int hashCode() {
        return (getId(), getName(), getSex());
    }

View source code