hashcode 討論總結

最主要的結論是如果兩個對象相等(equals()),那麼它們的hashCode一定相同,但如果兩個對象不同,它們的hashCode也有可能相同。這個結論供我們對類似生成ID這樣的對象標誌的算法的選擇上提供參考。

 

The text with italic style is from javadoc

1) if two objects are equal, then their hashCode must be the same
2) if two objects are not equal, their hashCode do NOT have to be distinct.
   It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the    hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
3) Class String overrides function hashCode(), it's implemented by the calculations on the string values.

4) contract #1 and #2 also work for class String, despite that it overrides function equals() and hashCode()
5) Typically, hashCode() for java.lang.Object is implemented by converting internal address of the object to an integer, therefore, on 32bit platform, As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. 
6) function hashCode() will be used for hashtable, so the confliction rate will impact the performance.

發佈了67 篇原創文章 · 獲贊 9 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章