- 如果您設計了一個新類並嘗試將該類的對象插入到HashSet或HashMap而未定義hashCode()方法,會發生什麼?
請保持說明容易。我正在學習考試,而且我仍然在Java中使用哈希來生鏽。謝謝。HashSet或HashMap沒有在新類中定義hashCode()方法
請保持說明容易。我正在學習考試,而且我仍然在Java中使用哈希來生鏽。謝謝。HashSet或HashMap沒有在新類中定義hashCode()方法
不會發生任何事情:-)
的每個對象都有自己的hashCode從對象類繼承()方法。所以,你的每一個新對象都是獨一無二的。通過自己,它們將被HashSet或HashMap識別爲唯一。
下面是官方的意見:
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code 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.
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code 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.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {@code 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.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
一個HashMap將數據存儲到項(也稱爲桶或桶)的多單鏈表。所有列表都在Entry(Entry []數組)中註冊
下圖顯示了具有可爲空條目的數組的HashMap實例的內部存儲。每個條目可鏈接到另一個條目以形成鏈接列表。
當用戶調用put(K key,V value)或get(Object key)時,該函數將計算Entry應該在的存儲桶的索引。
桶的索引(鏈表)使用密鑰的哈希碼生成。 因此,如果您已經重寫了hashCode方法,它將使用重寫方法來計算存儲區的索引 否則將使用默認哈希碼,這是您的對象的內存地址。所以在那種情況下,即使你的對象是你的地圖上會有一個新的條目。所以即使你試圖存儲邏輯上相同的對象。他們將被重新編號爲不同的哈希映射。
儘管合理實用,類Object定義的hashCode方法確實爲不同的對象返回不同的整數。 (這一般是通過將該對象的內部地址轉換成一個整數來實現的,但不是由的JavaTM編程語言不需要這種實現技巧。)
例如:
MyObject a = new MyObject("a", 123,"something");
MyObject b = new MyObject("a", 123,"something");
a and b will have different hashcodes.
你能對此進行測試你只需要幾行代碼? – andrel
看看[這個](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java)。如果你不重寫'hashCode()',那麼對'HashSet'特別是一個問題,因爲集合應該沒有重複,沒有重寫的每個對象都將被假定爲唯一的(即使它們不是)。 –