Java中HashMap的内部工作原理
函数‘hashCode’用于获取Java中对象的哈希码。这是超类 Object 的一个对象。它将对象引用的内存作为整数返回。它是一个原生函数,这意味着Java中不能直接使用方法来获取对象的引用。
为了提高HashMap的性能,请正确使用hashCode()。基本上,该函数用于计算存储桶和索引值。它的定义方式如下 -
public native hashCode()登录后复制
Capacity = number of buckets * load factor登录后复制
生成索引值,使数组的大小不会很大,从而避免 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"))); } }登录后复制