As you know, equals and Hashcode are two important methods of the java.lang.Object class. They often need to be overridden in practice.

The equals rule is used to compare the memory addresses of two objects. Whereas hashcode is a native method, Java memory is safe, so you can’t get the memory address of the object from the hashcode, but in fact, hashcode is derived from the memory address of the object through a hash algorithm.

This is an example of how to rewrite Student’s equals and HashCode methods. It is recommended that you use Eclipse to generate the equals and HashCode methods automatically.

There are now two Student objects:

Student s1=new Student(“小 小 “,18);

Student s2=new Student(“小 小 “,18);

S1.equals (s2) must return true

If we overwrite equals but not hashcode, then the Student hashcode method is the default hashcode method of Object. =s2, so their hashcodes are not necessarily equal.

However, overwriting equals, s1.equals(s2) returns true. According to the hashcode rule, two objects that are equal must have the same hash value. Therefore, overwriting equals must overwrite hashcode. And as you can see from the Student class’s overwritten HashCode method, the new hash returned by the overwritten Student is related to two attributes of Student.

Here are some rules about Hashcode:

If two objects are equal, hashCode must be equal

Two objects are not equal, hashCode is not necessarily equal

Hashcode is equal. Two objects are not necessarily equal

Hashcode is not equal, two objects must not be equal

  • Thumb up 40
  • collection
  • share
    • The article reported


keep@
Direct messages
Focus on