How to Obtain the Hash Code of an Object in Java 


               


How to Obtain the Hash Code of an Object in Java

Java


In this article, we show how to obtain the hash code of an object in Java.

Every Java object has a hash code, which is an integer representation of the class that's useful for certain operations.

The method isn't that important until you start to work with hash tables, which is a pretty advanced concept.

However, we will show how to obtain the hash code of an object in Java.

It's a fairly easy thing to do in Java because Java has a built-in hashCode() function that returns the value of the hash code as an integer.

You do not have to declare this hashcode(). It's a built-in function that you can just use.

To obtain the hash code of an object, we use the object name, followed by a dot, and the hashcode() function.

This is shown below.



So you simply take the object name, followed by a dot, and the hashcode() function.

To output the hash code, you would simply pass it into the System.out.println() function.

So below we show how to build a complete Java program that displays the hash codes for objects that have been created.



So above we create a class named Students.

In this class we have 2 variables, a String named name and an int named age. These represent the name and age of the a student object.

We then create the constructor of the class. This accepts a String named name and an int named age. In the body of the constructor, we then set the object name and age property to the name and age passed into the object when it is instantiated.

This is all the code in our Students class.

We next create the test class to test out this class and create objects and get their hash codes.

Java Test Class

The code below, the Studentsdemo class, creates objects of the Students class and gets the objects' hash codes.



Java Output


2018699554
1311053135
118352462
1550089733



So the output above shows the hash codes of the 4 objects we created in the studentsdemo class. You can see that their integers and that they may vary in length. The hash codes generated from the program you write will almost invariably be different than the hash codes seen above.

So going over the complete studentsdemo class, we put the main method in our class, because we want the computer to execute the code run in this class.

We are 4 student objects, as you can see above.

After this, we use System.out.println() function and place the object name, followed by a dot, and the hashcode() function.

These lines get all the hash codes for the objects we've created.

And this is all that is required to obtain hash codes of objects in Java.

As stated before, it's used when working with hash tables in Java.


HTML Comment Box is loading comments...