爲何重寫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

相關文章
相關標籤/搜索