Java Object 之hashCode

許佳佳233發表於2017-03-23

官方參考:

int hashCode ()
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

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 hash tables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

筆者翻譯:

返回一個物件的雜湊編碼值。這個方法支撐了雜湊表的優勢。(就像那些被HashMap所提供的一樣)

hashCode大致的條約如下:
1、倘若該物件與equals 的對照中是沒有資訊被修改的,一個相同的物件調無論在Java應用的可執行程式中的哪兒呼叫呼叫,hashCode這個方法都必須返回同一個整數。這個整數不需要在兩個可執行應用之間一直保持。
2、如果兩個物件在equals(Object)這個方法中是相等的,那麼這兩個物件呼叫hashCode方法必然也產生相同的整數結果。
3、如果兩個物件呼叫equals(Object)這個方法中的值是不相等的,他們呼叫hashCode方法返回的值有可能相等。但是,開發者必須明白,為不同的物件創造不同的整數結果是有益於雜湊表的。

hashCode方法被Object類定義來對不同的物件返回不同的整數值是很實用的。(這個經常會被用來把一個內部地址轉化為一個整數,但是這個應用技術在Java語言中不是很需要)

相關文章