How to override the hashCode method in Java?

To rewrite the hashCode() method, you need to follow the following steps:

  1. The method hashCode()
  2. Integer
  3. Return the hash code value for the object.
  4. equals() means comparing two objects to determine if they are equivalent.
  5. Returns a unique identifier for an object.
  6. Items
  7. Compute the hash value

Here is an example demonstrating how to rewrite the hashCode() method.

public class Person {
    private String name;
    private int age;
    
    // 构造函数和其他方法...
    
    // 重写hashCode()方法
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
    
    // 重写equals()方法
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        
        Person person = (Person) obj;
        return age == person.age && Objects.equals(name, person.name);
    }
}

In the example above, the hashCode() method utilizes the Objects.hash() method to calculate the hash code. This method automatically computes the hash code based on the provided parameters. In this example, we use the name and age properties to calculate the hash code, which are also utilized in the equals() method.

It is important to rewrite the equals() method when rewriting the hashCode() method to ensure the correct behavior of the object in hash collections like HashSet.

bannerAds