What is the HashSet.hashCode() method in Java?

The HashSet.hashCode() method is present in the HashSet class inside the java.util package. The method obtains the hash code value for this instance of the HashSet.

Parameter

HashSet.hashCode() doesn’t accept any parameters.

Return value

The HashSet.hashCode() method returns an integer value which is the hash code value for that instance of the HashSet.

Code

Let’s have a look at the code:

import java.io.*;
import java.util.HashSet;
class Main
{
public static void main(String args[])
{
HashSet<Integer> hash_set1 = new HashSet<Integer>();
hash_set1.add(1);
hash_set1.add(8);
hash_set1.add(5);
hash_set1.add(3);
hash_set1.add(17);
System.out.println("hash_set1 hashCode value is: " +
hash_set1.hashCode());
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we make the Main class.

  • In line 6, we make the main() function.

  • In line 8, we declare a HashSet of the integer type, i.e., hash_set2.

  • In lines 9 to 13, we add the elements into the HashSet using the HashSet.add() method.

  • In line 15, we display the result of the Hashset’s hash code value using the HashSet.hashCode() with a message.

Free Resources