Java SortedMap hashCode()方法及示例

来源:这里教程网 时间:2026-02-17 21:11:24 作者:

Java SortedMap hashCode()方法及示例

Java中SortedMap接口的 hashCode() 方法用于为给定的包含键和值的地图生成一个hashCode。

语法

int hashCode()

参数: 该方法没有参数。

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

注意 :SortedMap中的hashCode()方法是继承自Java中的Map接口。

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

程序1:

// Java code to show the implementation of// hashCode() method in SortedMap interface  import java.util.*;  public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a SortedMap        // of type TreeMap        SortedMap<Integer, String> map            = new TreeMap<>();          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 SortedMap interface  import java.util.*;  public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a SortedMap        // of type TreeMap        SortedMap<String, String> map            = new TreeMap<>();          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文档

相关推荐