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.
hashCode()
methodIn 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.
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());}}}
Lines 3&4: We defined two variables a
and b
in which we stored 200 as their value for both.
Lines 6-9: We defined the if
condition that checks whether both variable's hash value is the same or not.
Lines 11-17: We repeated the same code that we used in lines 3-9 but this time we stored different values for both variables.
Learning hash codes in Java is crucial for efficient data retrieval and manipulation, especially when working with collections. By providing a unique numeric representation for objects, hash codes facilitate fast lookup and storage operations. However, it's important to ensure that the hash code generation is consistent with the object's equality comparison logic to maintain correctness and efficiency in data structures and algorithms.