爲什麼重寫equals()和hashcode()

首先寫個例子
public class TestTest{

    String name ;
    TestTest(String name){
        this.name = name;
    }
public static void main(String[] args){
    TestTest test1 = new TestTest("hello");
    TestTest test2 = new TestTest("hello");

    System.out.println("輸出test1是否等於test2:"+test1.equals(test2));//如果不重寫equals()兩者不等,重寫相等

    Map<TestTest, String> map = new HashMap<>(4);
        map.put(test1, "hello");
    String hello = map.get(test2);
    System.out.println(hello);//結果爲null,添加重寫後會拿到hello
}

//添重寫後

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    TestTest testTest = (TestTest) o;
    return name.equals(testTest.name);
}

@Override
public int hashCode() {
    return Objects.hash(name);
}
}

因爲默認情況下會調用Object的equals(),hashcode(),而map中get時get獲取的hashCode是hashMap中的hash()來獲取地址所以不一致,這也是爲什麼通常用String或Integer等final 並且重寫了hashCode和equals類來做鍵值來防止鍵值被重寫。下圖是object的兩個被重寫的方法:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章