Java Set hashCode()方法及示例
Java中 Set 的 hashCode() 方法是用来获取Set实例的hashCode值的。它返回一个整数,该整数是Set的这个实例的hashCode值。
语法
public int hashCode()
参数: 该函数没有参数。
返回: 该方法返回一个整数,该整数是Set的这个实例的hashCode值。
下面的例子说明了Set.hashCode()方法。
例1 :
// 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
Set<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 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
Set<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 Set
System.out.println("Set: " + arr);
// Get the hashCode value
// using hashCode() value
System.out.println("HashCode value: "
+ arr.hashCode());
}
}
输出。
Set: [ForGeeks, Geeks, For, GeeksForGeeks]
HashCode value: -482506029
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#hashCode()