Hashcode() in Java
Introduction
In computer science, hashing is a concept that involves mapping entities or objects to integer values. The values of those entities are called hashcodes or hash values.
In Java, to compute hash values of objects, the hashCode() method is used. In Java, the Integer class has two methods:
- hashCode(): It computes the hash values of the Integer.
- hashCode(int value): It computes the hash values of primitive int values.
Properties of Hashing
- When the output of the equals() method is the same as the object then they have the same hash value. That means they need to be mapped to the same Integer value.
- When two objects are not equal, they may or may not have the same hash values. That is why different objects do not need to have different hash values.
- When hash values of objects are computed multiple times, their hash values should remain consistent.
- When invoked more than once during the execution, the output of hashing algorithm must be the same for the same objects.
- But, from one execution to another execution the value does not need to stay consistent.
Java hashCode() Method
To compute the hash values of input objects, there is the hashCode() method in java. The value of that integer which represents the input object’s hash value, that integer is returned.
To produce the hash values of objects, the hashCode() method is used. These objects are then stored in Java collections such as HashMap, HashSet and HashTable by using these hash values.
In this example, we will see the properties of hashing by testing the following things:
Two objects having the same values also have the same hashcodes.
Objects that do not have the same values also don’t have the same hashcodes.
When the hashcodes of the same object are computed again, it gives the same hashcode or the hashcode is consistent.
Code
import java.io.*; |
Output:
HashCode of a1 = 100 is: 48625 |
Integer class hashCode(int value) Method
As can be seen clearly, this method computes the hash value of its parameter and return its hashcode.
Code
// Example of hashCode(int value) |
Output:
HashCode of value = 144 is : 144 |