为什么重写equals()和hashcode()
生活随笔
收集整理的這篇文章主要介紹了
为什么重写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的兩個被重寫的方法:
?
總結
以上是生活随笔為你收集整理的为什么重写equals()和hashcode()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gerrit的Change-Id机制和h
- 下一篇: 前端数据可视化可绘制地图等插件:High