Open In App

Set hashCode() Method in Java

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the hashCode() method is defined in the Object class and is used to generate a hash code for objects. It plays a very important role in hash-based collections like HashMap, HashSet, and HashTable.

Example 1: This example demonstrates how hashCode() is used to get the hash code of the HashSet.


Output
Set: [1, 2, 3, 4]
HashCode value: 10

Syntax of hashCode() Method

public int hashCode()

  • Parameter: This method does not take any parameter.
  • Return Type: This method return an int value.

Example 2: This example demonstrates that without overriding hashCode(), different objects with similar data have different hash codes.


Output
hashCode of obj1: 1510467688
hashCode of obj2: 868693306

Next Article

Similar Reads