首頁  >  文章  >  Java  >  Java中HashMap的內部運作原理

Java中HashMap的內部運作原理

WBOY
WBOY轉載
2023-08-28 13:37:461257瀏覽

Java中HashMap的內部運作原理

函數‘hashCode’用來取得Java中物件的雜湊碼。這是超類別 Object 的一個物件。它將物件引用的記憶體作為整數傳回。它是一個原生函數,這意味著Java中不能直接使用方法來取得物件的參考。

為了提升HashMap的效能,請正確使用hashCode()。基本上,該函數用於計算儲存桶和索引值。它的定義方式如下 -

public native hashCode()

既然我們提到了“桶”,那麼理解它的含義就很重要了。它是用於儲存節點的元素。一個桶子中可以有兩個以上的節點。節點可以使用鍊錶資料結構連接。 hashmap的容量可以透過bucket和負載因子來計算。

Capacity = number of buckets * load factor

函數「equals」用於檢查兩個物件之間的相等性。它也是由超類別 Object 給出的。透過提供自訂實現,可以在自訂類別中重寫此函數。此函數根據問題中的兩個物件是否相等傳回 true 或 false。

產生索引值,讓陣列的大小不會很大,從而避免 outOfMemoryException。尋找陣列索引的公式是-

Index = hashCode(key) & (n-1) – Here n refers to number of buckets.

讓我們看一個範例-

範例

 現場示範

import java.util.HashMap;
class hash_map{
   String key;
   hash_map(String key){
      this.key = key;
   }
   @Override
   public int hashCode(){
      int hash = (int)key.charAt(0);
      System.out.println("The hash code for key : " + key + " = " + hash);
      return hash;
   }
   @Override
   public boolean equals(Object obj){
      return key.equals(((hash_map)obj).key);
   }
}
public class Demo{
   public static void main(String[] args){
      HashMap my_map = new HashMap();
      my_map.put(new hash_map("This"), 15);
      my_map.put(new hash_map("is"), 35);
      my_map.put(new hash_map("a"), 26);
      my_map.put(new hash_map("sample"), 45);
      System.out.println("The value for key 'this' is : " + my_map.get(new hash_map("This")));
      System.out.println("The value for key 'is' is: " + my_map.get(new hash_map("is")));
      System.out.println("The value for key 'a' is: " + my_map.get(new hash_map("a")));
      System.out.println("The value for key 'sample' is: " + my_map.get(new hash_map("sample")));
   }
}

輸出

The hash code for key : This = 84
The hash code for key : is = 105
The hash code for key : a = 97
The hash code for key : sample = 115
The hash code for key : This = 84
The value for key 'this' is : 15
The hash code for key : is = 105
The value for key 'is' is: 35
The hash code for key : a = 97
The value for key 'a' is: 26
The hash code for key : sample = 115
The value for key 'sample' is: 45

名為「hash_map」的類別定義了一個字串和一個建構子。這被另一個名為“hashCode”的函數覆蓋。這裡,hashmap的鍵值被轉換為整數並列印哈希碼。接下來,「equals」函數被重寫並檢查鍵是否等於雜湊圖的鍵。類別 Demo 定義了一個 main 函數,在該函數中建立 HashMap 的新實例。使用“put”函數將元素新增至此結構並列印在控制台上。

以上是Java中HashMap的內部運作原理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除