Java中的Map hashCode()方法及示例

Java中的Map hashCode()方法及示例

该方法用于为给定包含键和值的映射生成hashCode。

语法:

int hashCode()

参数: 此方法无参数。

返回值: 该方法返回给定映射的hashCode值。

下面的程序展示了int hashCode()方法的实现。

程序1:

// Java代码展示Map接口中hashCode方法的实现
import java.util.*;
public class GfG {
  
    // 主函数
    public static void main(String[] args)
    {
  
        // 初始化类型为HashMap的Map
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "One");
        map.put(3, "Three");
        map.put(5, "Five");
        map.put(7, "Seven");
        map.put(9, "Ninde");
        System.out.println(map);
  
        int hash = map.hashCode();
  
        System.out.println(hash);
    }
}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Ninde}
238105666

程序2: 以下是展示hashCode()的实现的代码。

// Java代码展示Map接口中hashCode方法的实现
import java.util.*;
public class GfG {
  
    // 主函数
    public static void main(String[] args)
    {
  
        // 初始化类型为HashMap的Map
        Map<String, String> map = new HashMap<>();
        map.put("1", "One");
        map.put("3", "Three");
        map.put("5", "Five");
        map.put("7", "Seven");
        map.put("9", "Ninde");
        System.out.println(map);
  
        int hash = map.hashCode();
  
        System.out.println(hash);
    }
}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Ninde}
238105618

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程