Java AbstractMap hashCode()方法及示例

Java AbstractMap hashCode()方法及示例

Java中的AbstractMap.hashCode()方法是用来获取一个特定的AbstractMap的哈希代码值。一个地图由若干个桶组成,用来存储键值对。每个桶都有一个唯一的标识,当一个键值对被插入到一个桶中时,键的哈希码与桶的标识符相匹配,如果其匹配,键值对就被成功存储。这就是哈希码的工作原理。

语法

AbstractMap.hashCode()

参数: 该方法不接受任何参数。

返回值: 该方法返回地图的哈希码值。

下面的程序用来说明AbstractMap.hashCode()方法的工作。

程序1: 将字符串值映射到整数键。

// Java code to illustrate the hashCode() method
  
import java.util.*;
  
public class Abstract_Map_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty AbstractMap
        AbstractMap<Integer, String>
            abs_map = new IdentityHashMap<Integer, String>();
  
        // Mapping string values to int keys
        abs_map.put(10, "Geeks");
        abs_map.put(15, "4");
        abs_map.put(20, "Geeks");
        abs_map.put(25, "Welcomes");
        abs_map.put(30, "You");
  
        // Displaying the AbstractMap
        System.out.println("Initial Mappings are: "
                           + abs_map);
  
        // Getting the hashcode value for the map
        System.out.println("The hashcode value of the map: "
                           + abs_map.hashCode());
    }
}

输出。

Initial Mappings are: {10=Geeks, 30=You, 20=Geeks, 25=Welcomes, 15=4}
The hashcode value of the map: 2043437408

程序2: 将整数值映射到字符串键。

// Java code to illustrate the hashCode() method
  
import java.util.*;
  
public class Abstract_Map_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty AbstractMap
        AbstractMap<String, Integer>
            abs_hash = new IdentityHashMap<String, Integer>();
  
        // Mapping int values to string keys
        abs_hash.put("Geeks", 10);
        abs_hash.put("4", 15);
        abs_hash.put("Geeks", 20);
        abs_hash.put("Welcomes", 25);
        abs_hash.put("You", 30);
  
        // Displaying the AbstractMap
        System.out.println("Initial Mappings are: "
                           + abs_hash);
  
        // Getting the hashcode value for the map
        System.out.println("The hashcode value of the map: "
                           + abs_hash.hashCode());
    }
}

输出。

Initial Mappings are: {Geeks=20, Welcomes=25, You=30, 4=15}
The hashcode value of the map: 751311572

注意: 同样的操作可以在任何类型的Mapping中进行,不同数据类型的变化和组合。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程