【Java开发规范】hashCode 和 equals 的处理规则

(1)只要覆写 equals,就必须覆写 hashCode。

说明:因为 Set 存储的是不重复的对象,依据 hashCode 和 equals 进行判断,所以 Set 存储的对象必须覆写这两种方法。

(2)如果自定义对象作为 Map 的键,那么必须覆写 hashCode 和 equals。

说明:String 因为覆写了 hashCode 和 equals 方法,所以可以愉快地将 String 对象作为 key 来使用。

public class Person {
    private String name;
    private int age;
    private boolean gender;
 
    public Person() {
        super();
    }
 
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isGender() {
        return gender;
    }
    public void setGender(boolean gender) {
        this.gender = gender;
    }
 
    @Override
    public boolean equals(Object another) {
        if (this == another) {
            return true;
        }
        if (another instanceof Person) {
            Person anotherPerson = (Person) another;
            if (this.getName().equals(anotherPerson.getName()) && this.getAge() == anotherPerson.getAge()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
 
    @Override
    public int hashCode() {
        int hash = 17;
        hash = hash * 31 + getName().hashCode();
        hash = hash * 31 + getAge();
        return hash;
    }
}
经验分享 程序员 微信小程序 职场和发展