📜  Java中的 AbstractSet hashCode() 方法及示例

📅  最后修改于: 2022-05-13 01:54:42.952000             🧑  作者: Mango

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

Java AbstractSet中的AbstractSet.hashCode()方法用于获取特定此 AbstractSet 的哈希码值。一个集合由许多存储元素的桶组成。每个桶都有一个唯一的标识,当一个元素被插入到桶中时,它的哈希码与桶的标识符匹配,如果匹配,则元素存储成功。这就是哈希码的工作原理。

句法:

AbstractSet.hashCode()

参数:该方法不接受任何参数。

返回值:该方法返回集合的哈希码值

以下程序用于说明 AbstractSet.hashCode() 方法的工作原理:

方案一:

// Java code to illustrate the hashCode() method
  
import java.util.*;
  
public class Abstract_Set_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty AbstractSet
        AbstractSet
            abs_set = new HashSet();
  
        // Adding elements into the set
        abs_set.add("Geeks");
        abs_set.add("4");
        abs_set.add("Geeks");
        abs_set.add("Welcomes");
        abs_set.add("You");
  
        // Displaying the AbstractSet
        System.out.println("Initial Set is: "
                           + abs_set);
  
        // Getting the hashcode value for the set
        System.out.println("The hashcode value of the set: "
                           + abs_set.hashCode());
    }
}
输出:
Initial Set is: [4, Geeks, You, Welcomes]
The hashcode value of the set-295204749

方案二:

// Java code to illustrate the hashCode() method
  
import java.util.*;
  
public class Abstract_Set_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty AbstractSet
        AbstractSet
            abs_set = new TreeSet();
  
        // Adding elements into the set
        abs_set.add(15);
        abs_set.add(20);
        abs_set.add(30);
        abs_set.add(40);
        abs_set.add(50);
  
        // Displaying the AbstractSet
        System.out.println("Initial Set is: "
                           + abs_set);
  
        // Getting the hashcode value for the set
        System.out.println("The hashcode value of the set: "
                           + abs_set.hashCode());
    }
}
输出:
Initial Set is: [15, 20, 30, 40, 50]
The hashcode value of the set: 155

注意:可以对任何类型的 Set 执行相同的操作,其中包含不同数据类型的变化和组合。