那么為什么在重寫equals方法的時候需要重寫hashCode方法呢?
主要是Object.hashCode的通用約定:
a. 在java應用程序運行時,無論何時多次調用同一個對象時的hsahCode()方法,這個對象的hashCode()方法的返回值必須是相同的一個int值.
b. 如果兩個對象equals()返回值為true,則他們的hashCode()也必須返回相同的int值.
c. 如果兩個對象equals()返回值為false,則他們的hashCode()返回值也必須不同.
String s1 = new String("1111"); String s2 = new String("1111"); s1.hashCode(); s2.hashCode(); System.out.println(s1.equals(s2));
s1和s2對象所指的內存地址是不一樣的,一個對象的hashcode是內存地址進行hash運算而得,如果string沒有重寫hashcode,那么s1和s2的hashcode 也有可能是不一樣的。如果用Obejct的equals方法,那么比較的手機兩個對象在堆內存的地址,那么結果會是是false,但是在業務系統中我們需要的是對象屬性是否一致,所以重寫了equals方法。string的底層數據結構是char數組,所以重寫equals的邏輯就是兩個對象的char數組循環比較值。那么equals重寫了,但是如果hashcode沒有重寫那就違反了Object.hashCode的通用約定,所以hashCode必須也重寫。可以從源碼看出,兩個值相等的String 的hashCode一定相等。
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
參考 JavaBean關於為什么要重寫hashCode()方法和equals()方法及如何重寫_阿武剛巴得-CSDN博客