Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
  }
}
Using the hashset.hashCode() function in Java

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring