簡體   English   中英

HashSet 或 HashMap 沒有在新類中定義 hashCode() 方法

[英]HashSet or HashMap without defining a hashCode() method in a new class

  • 如果您設計一個新類並嘗試將該類的對象插入 HashSet 或 HashMap 而不定義 hashCode() 方法,會發生什么情況?

請保持簡單的解釋。 我正在為考試而學習,但我仍然對 Java 中的哈希感到生疏。 謝謝你。

HashMap 將數據存儲到多個單向鏈接的條目列表(也稱為桶或箱)中。 所有列表都注冊在一個Entry數組中(Entry[]數組)

下圖顯示了一個帶有可空條目數組的 HashMap 實例的內部存儲。 每個 Entry 可以鏈接到另一個 Entry 以形成一個鏈表。

當用戶調用 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.

什么都不會發生:-)

每個對象都有自己的 hashCode() 方法,該方法繼承自Object類。 因此,您的每個新對象都將是獨一無二的。 由她自己,它們將被 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&trade; 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM