Java Object hashCode()

The syntax of the hashCode() method is:

object.hashCode()

hashCode() Parameters

The hashCode() method does not take any parameters.


hashCode() Return Values

  • returns the hash code value of the object

Note: The hash code value is an integer value associated with each object. It is used to identify the location of objects in the hash table.


Example 1: Java Object hashCode()

Note: The Object class is the super class for all the classes in Java. Hence, every class can implement the hashCode() method.


Example 2: hashCode() with String and ArrayList

In the above example, we can call the hashCode() method to get the hash code of the String and ArrayList object.

It is because the String and ArrayList class inherit the Object class.


Example 3: Hash Code Value for Equals Object

In the above example, we can see that two objects obj1 and obj2 are generating the same hash code value.

It is because two objects are equal. And, according to official Java documentation, two equal objects should always return the same hash code value.

Note: We have used the Java Object equals() method to check whether two objects are equal.