为何重写equals()方法为何要重写hashCode()方法

定义一下命题:java

相等: 若是A和B相等,则A.equals(B)为true:若是A.equals(B)为true,则A和B相等;ide

相同:若是A和B相同,则A.hashCode() == B.hashCode(); 若是A.hashCode() == B.hashCode(); 则A和B相同this

此问题的解释就会是:spa

若是只重写equals()方法,就会出现相等的两个对象不相同, 若是只重写hashCode()方法,就会出现相同的两个对象不相等。code

案例1, 只重写equals()方法

public class Person {

    private final String name;

    public Person(String name) {
        this.name = name;
    }

    /**
     * 只重写{@link #equals(Object)} 方法, 变成只要名称是相同对象,则两{@code Person}相等
     *
     * @param other 另外一个对象
     * @return {@code true} : 两个两{@code Person}相等
     */
    @Override
    public boolean equals(Object other) {
        if (this == other) return true;

        if (other == null || getClass() != other.getClass()) return false;

        Person person = (Person) other;
        return Objects.equals(name, person.name);
    }
}
public static void main(String[] args) {
    String name = "张三";

    Person a = new Person(name);
    Person b = new Person(name);

    System.out.print("Person a 的HashCode : '" + a.hashCode() + "'");
    System.out.println("\tPerson b 的HashCode : '" + b.hashCode() + "'");

    //只要HashCode同样,则证实两对象相同
    System.out.print("Person a  和  Person b " + (a.hashCode() == b.hashCode() ? "" : "不") + "相同!");
    System.out.println("\t 但 Person a  和  Person b " + (a.equals(b) ? "" : "不") + "相等!");
}

image-20200414225502236.png

案例2, 只重写hashCode()方法

public class Person {

    private final String name;

    public Person(String name) {
        this.name = name;
    }

    /**
     * 只重写{@link #hashCode()}方法,相同hashCode的对象不向等
     * @return hash code 值
     */
    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}
public static void main(String[] args) {
    String name = "张三";

    Person a = new Person(name);
    Person b = new Person(name);

    System.out.print("Person a 的HashCode : '" + a.hashCode() + "'");
    System.out.println("\tPerson b 的HashCode : '" + b.hashCode() + "'");

    //只要HashCode同样,则证实两对象相同
    System.out.print("Person a  和  Person b " + (a.hashCode() == b.hashCode() ? "" : "不") + "相同!");
    System.out.println("\t 但 Person a  和  Person b " + (a.equals(b) ? "" : "不") + "相等!");
}

image-20200414230008213.png

java 中对hash code有个通用的规定,即相等的对象必须拥有相等的hash code,就是说若是两个对象调用equals()方法相等,则它们调用hashCode()所获得的hash code值也相等,所以重写equals()方法要重写hashCode()方法!对象

那么重写hashCode()方法,是否是也须要重写equals()?,若是是那么可不能够说明相等hash code的对象也相等?,据我所知,好像并无这个要求。blog

相关文章
相关标签/搜索