Why rewrite the hashCode and equals methods in the hash table

1. Why overwrite hashCode and equals?

We create a new person class:

public class Person {
    
    
    String name;
    int age;
    public Person(String name,int age){
    
    
        this.age=age;
        this.name=name;
    }

}

Two new objects, p1 and p2, are expected to show true after running, and p1 and p2 are hoped to point to the same object, but the running results are as follows:

import java.util.HashSet;

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        Person p1=new Person("小艾",18);
        Person p2=new Person("小艾",18);
//        HashMap<Person,String> map=new HashMap<>();
//        map.put(p1,"小艾");
//        System.out.println(map.get(p2));
        HashSet<Person> set=new HashSet<>();
        set.add(p1);
        System.out.println(set.contains(p2));

    }
}

Insert picture description here
The operation result is false, if you want to return true, you must override the hashCode method and the equals method

 @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
    
    
        return Objects.hash(name, age);
    }

Insert picture description here
Why do the two objects refer to the same object after overriding these two methods? If only one of them is overwritten, can it return true? The answer is definitely no, you can try it on your own software.

Second, cause analysis

1.hashCode introduction:

The function of hashCode() is to obtain the code, also known as the hash code. It actually returns an integer of type int . The function of this hash code is to determine the index position of the object in the hash table. HashCode() is defined in Object.java of the JDK, which means that any class in Java contains the hashCode() function. The hash table stores key-value pairs. Its characteristics are: The "key" quickly retrieves the corresponding "value", which uses the hash code! (Hash code can quickly find the desired object).

2. Why HashCode

Let’s take " How does HashSet check for duplication " as an example to explain why there is a hashCode:
When you add an object to a HashSet, HashSet will first calculate the object’s hashCode value to determine where the object is added, and will also compare it with other objects that have been added The hashcode value is compared. If there is no matching hashcode, HsahSet will assume that the object does not appear repeatedly. But if objects with the same hashcode value are found, the equals() method will be called to check whether the objects with equal hashcodes are really the same. If the two are the same, HashSet will not let it join the operation successfully. If they are different, they will be re-hashed to another location. (Excerpt from the second edition of my Java book "Head first java"). In this way, we greatly reduce the number of equals, and accordingly greatly improve the execution speed. That's pretty clear.

to sum up

Relevant rules for hashCode() and equals() rewriting :
1. If the two objects are equal, the hashCode must also be equal;
2. If the two objects are equal, call the equals method on the two objects, and both return true;
3 . Two objects have the same hashCode value, that is, p1.hashCode()==p2.hashCode(), they are not necessarily equal, because hash conflicts may occur;
4. Therefore, the equals method has been overwritten, then The hashCode method must also be overridden;
5. The default behavior of hashCode () is to generate unique values ​​for objects on the heap. If hashCode() is not overridden, the two objects of the class will not be equal anyway (even if the two objects point to the same data).

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/109633780