函数‘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 = 84the hash code for key : is = 105the hash code for key : a = 97the hash code for key : sample = 115the hash code for key : this = 84the value for key 'this' is : 15the hash code for key : is = 105the value for key 'is' is: 35the hash code for key : a = 97the value for key 'a' is: 26the hash code for key : sample = 115the value for key 'sample' is: 45
名为“hash_map”的类定义了一个字符串和一个构造函数。这被另一个名为“hashcode”的函数覆盖。这里,hashmap的键值被转换为整数并打印哈希码。接下来,“equals”函数被重写并检查键是否等于哈希图的键。类 demo 定义了一个 main 函数,在该函数中创建 hashmap 的新实例。使用“put”函数将元素添加到此结构中并打印在控制台上。
以上就是java中hashmap的内部工作原理的详细内容。
