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

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

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

语法

public int hashCode()

参数: 此函数没有参数。

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

下面的例子说明了HashSet.hashCode()方法。

例1 :

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

输出:

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

例2 :

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

输出:

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程