为什么重写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的两个被重写的方法:

 

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