Java AbstractSet hashCode()方法及示例

Java AbstractSet hashCode()方法及示例

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

语法

AbstractSet.hashCode()

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

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

下面的程序用来说明AbstractSet.hashCode()方法的工作。

程序 1 :

// 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<String>
            abs_set = new HashSet<String>();
  
        // 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

程序 2:

// 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<Integer>
            abs_set = new TreeSet<Integer>();
  
        // 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中进行,不同数据类型的变化和组合。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程