Java overwrite equals method, why is it recommended to overwrite hashCode method together

We all know the difference between using == and overriding the equals method when judging whether objects are equal. By default, equals is also implemented by == comparing addresses, so when we want to compare based on the specific content of the object (such as judging whether two students are the same person, we can determine by comparing the student ID: studentA .getId()==studentB.getId()), we will override the equals method:

//比如在Student类里
public boolean equals(Object obj) {
        Student t=(Student)obj;
        return (this.id == obj.id);
    }

 

Generally, the equals method is overwritten here, so why is it recommended to overwrite the hashCode() method together? We know that, by default, the hashCode() method is a native method, which compares the address of the object. If the object address is different, the returned hashCode is also different.

When we put an object in a collection, such as a Set, we first confirm the placement position through the value of the object's hashcode, and then judge whether there is duplicate data in the current position. If it is not overwritten, the hashcodes of studentA and studentB must be different and will be placed in different positions, so the function of Set deduplication will be invalid.

In summary, when Jdk recommends overriding equals, the hashCode method should also be overridden. It may not be used currently, but when it is used later, it may cause problems, such as when it involves collections.

Guess you like

Origin blog.csdn.net/u013821237/article/details/94397495