Java hashCode()
This blog will elaborate on using and implementing Java’s “hashCode()” method.
What is “hashCode()” in Java?
A “hash code” is an integer value associated with each Java object and returns a “4” bytes value. The “hashCode()” method is a Java Integer class method that gives the hash code for the provided inputs.
Syntax
In this syntax, “val” determines the hash code.
Example 1: Utilization of “hashCode()” Upon the Integer Objects
In this example, two integer objects can be created, and their corresponding “hash code” can be retrieved:
Apply the following steps, as given in the above code:
- First of all, create two “Integer” objects named “i” and “j” using the “new” keyword and the “Integer()” constructor, respectively, and allocate the specified integer values.
- After that, associate the “hashCode()” method with each of the created objects.
- Lastly, display the corresponding hash code against each integer object.
Output
In the above output, it can be observed that the corresponding hash codes against the integers are displayed.
Example 2: Utilization of “hashCode()” Upon the String Objects
In this specific example, the “hash code” against the “String” objects can be returned:
Apply the following steps in accordance with the above lines of code:
- Create two “String” objects named “i” and “j” and specify the string values.
- Now, associate the “hashCode()” method with each created object.
- Finally, return the hash codes of the string objects.
Output
The above output indicates that the corresponding “hash code” against the string values is displayed.
Conclusion
A hash code corresponds to an integer value associated with each Java object. The “hashCode()” method in Java gives the hash code for the provided inputs. This method can be applied to fetch the hash code of the “Integer” and “String” objects. This blog compiled the approaches to utilize Java’s “hashCode()” method.
Source: linuxhint.com