Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hashcode
java
communitycreator

What is Objects.hashCode() in Java?

abhilash

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.

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

RELATED TAGS

hashcode
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