Java中HashMap的内部工作原理

WBOY
WBOY 转载
2023-08-28 13:37:46 941浏览

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,如有侵犯,请联系admin@php.cn删除