Java中HashMap的內部工作原理
函式‘hashCode’用於獲取Java中物件的雜湊碼。這是超類Object的一個物件。它返回物件引用的記憶體作為整數。它是一個本地函式,這意味著Java中沒有直接的方法可以用來獲取物件的引用。
為了提高HashMap的效能,請正確使用hashCode()。基本上,此函式用於計算桶和索引值。其定義如下:
public native hashCode()
既然我們提到了“桶”,那麼瞭解它的含義很重要。它是一個用於儲存節點的元素。一個桶中可以有多個節點。這些節點可以使用連結串列資料結構連線起來。雜湊圖的容量可以透過桶和載入因子計算出來。
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’的函式覆蓋。在這裡,雜湊圖的鍵值被轉換為整數,並列印雜湊碼。接下來,‘equals’函式被覆蓋,並檢查鍵是否等於雜湊圖的鍵。類Demo定義了一個主函式,其中建立了一個HashMap的新例項。使用‘put’函式將元素新增到此結構中,並在控制檯上列印。
廣告