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
The syntax of the hashCode()
method is as follows.
public static int hashCode(Object o)
Object o
: the object whose hash code needs to be returned.The method returns the hash code of a non-null argument and zero for a null
argument.
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
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 , which is the code value of the array list.
1