Java SortedSet hashCode()方法及示例

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

Java SortedSet hashCode()方法及示例

Java中 SortedSethashCode() 方法是用来获取SortedSet实例的hashCode值的。它返回一个整数,这个整数就是这个SortedSet实例的hashCode值。

语法

public int hashCode()

参数: 该函数没有参数。

返回: 该方法返回一个整数值,该值是Set实例的hashCode值。

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

下面的例子说明了SortedSet.hashCode()方法的作用。

例1 :

// Java code to demonstrate the working of// hashCode() method in SortedSet  import java.util.*;  public class GFG {    public static void main(String[] args)    {        // creating an Set        SortedSet<Integer> arr            = new TreeSet<Integer>();          // using add() to initialize values        // [1, 2, 3, 4]        arr.add(1);        arr.add(2);        arr.add(3);        arr.add(4);          // print Set        System.out.println("Set: " + arr);          // Get the hashCode value        // using hashCode() value        System.out.println("HashCode value: "                           + arr.hashCode());    }}

输出:

Set: [1, 2, 3, 4]HashCode value: 10

例2 :

// Java code to demonstrate the working of// hashCode() method in Set  import java.util.*;  public class GFG {    public static void main(String[] args)    {        // creating an Set        SortedSet<String> arr            = new TreeSet<String>();          // using add() to initialize values        // [Geeks, For, ForGeeks, GeeksForGeeks]        arr.add("Geeks");        arr.add("For");        arr.add("ForGeeks");        arr.add("GeeksForGeeks");          // print Set        System.out.println("Set: " + arr);          // Get the hashCode value        // using hashCode() value        System.out.println("HashCode value: "                           + arr.hashCode());    }}

输出:

Set: [For, ForGeeks, Geeks, GeeksForGeeks]HashCode value: -482506029

参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#hashCode()

相关推荐