Java Map hashCode()方法及实例

Java Map hashCode()方法及实例

该方法用于为给定的包含键和值的Map生成一个hashCode。

语法

int hashCode()

参数: 该方法没有参数。

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

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

程序1:

// Java code to show the implementation of
// hashCode method in Map interface
import java.util.*;
public class GfG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Initializing a Map of type HashMap
        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 code to show the implementation of
// hashCode method in Map interface
import java.util.*;
public class GfG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Initializing a Map of type HashMap
        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

参考资料:
Oracle文档

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程