What is Objects.hashCode() in Java?

What is the hashCode method?

The hashCode() method is a static method of the Objects class. This method takes in an object and returns the input object’s hash code. The method returns zero if the passed object points to null.

Refer to What is the hashCode method in Java? to learn more about hash codes in Java.

To use the hashCode() method, you need to import the following module.

java.util.Objects

Syntax

The syntax of the hashCode() method is as follows.


public static int hashCode(Object o)

Parameters

  • Object o: the object whose hash code needs to be returned.

Return value

The method returns the hash code of a non-null argument and zero for a null argument.

Code

Example 1

In the code below, we pass the null value as an object to the method.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
Object input = null;
System.out.println(Objects.hashCode(input));
}
}

If we run the program, it should print zero.

0

Example 2

In the code below, we pass an array list as an object to the method:

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
List<String> input = new ArrayList<>();
System.out.println(Objects.hashCode(input));
}
}

If we run the program above, it should print 11, which is the code value of the array list.

1

Free Resources