Related Tags

What is a hash code in Java?


A hash code is an integer value that is associated with each object in Java. Its main purpose is to facilitate hashing in hash tables, which are used by data structures like HashMap.

The hashCode() method

In Java, the hash code value of an object is returned by calling the hashCode() method, on that object. This method is implemented, by default, in the Object class and is, therefore, inherited by user-defined classes as well.

This method returns the same integer value (when called on the same object during the same instance of a Java application), provided that no data used by the equals() method is modified.

When hashCode() is called on two separate objects (which are equal according to the equals() method) it returns the same hash code value. However, if it is called on two unequal objects, it will not necessarily return different integer values.

Code

The sample code below prints the hash codes of the same ​and different variables:

class Hash{
    public static void main(String[] args){
        String a = "200";
        String b = "200";

        if(a.equals(b)){
            System.out.println("Equal variables:");
            System.out.println(a.hashCode() + "\n" + b.hashCode());
        }

        String c = "10";
        String d = "50";

        if(!c.equals(d)){
            System.out.println("\nUn-equal variables:");
            System.out.println(c.hashCode() + "\n" + d.hashCode());
        }
    }
}
RELATED COURSES
View all Courses

Keep Exploring