重写equals() 和 hashCode()方法

使用《Effective Java》里的17和31散列码方法:

class Person {
    private String name;
    private int age;
    //getters and setters, constructor 
    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(!(obj instanceof Person)) return false;
        Person p = (Person)obj;
        return p.getName().equals(name) && p.getAge() == age;
    }
}

你可能感兴趣的:(Java笔记)