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()

class Main {
  public static void main(String[] args) {

    // hashCode() with Object
    Object obj1 = new Object();
    System.out.println(obj1.hashCode());  // 1785210046

    Object obj2 = new Object();
    System.out.println(obj2.hashCode());  // 1552787810

    Object obj3 = new Object();
    System.out.println(obj3.hashCode());  // 1361960727
  }
}

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

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {

    // hashCode() with String
    String str = new String();
    System.out.println(str.hashCode());  // 0

    ArrayList<Integer> list = new ArrayList<>();
    System.out.println(list.hashCode());  // 1
  }
}

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

class Main {
  public static void main(String[] args) {

    // hashCode() with Object
    Object obj1 = new Object();

    // assign obj1 to obj2
    Object obj2 = obj1;

    // check if two objects are equal
    System.out.println(obj1.equals(obj2));  // true

    // get hashcode of obj1 and obj2
    System.out.println(obj1.hashCode());   // 1785210046
    System.out.println(obj2.hashCode());   // 1785210046

  }
}

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.

Did you find this article helpful?