hashCode() vs equals(): About Hash code
hashCode() is a method of Object class. Hash code is an integer representation of an object by JVM. Hash code is system generated using some formula (let us not go much of detais of formula). Hash codes generated need not be the same for different times of execution. Internally, the objects are stored in Hashtable format. The equals() method, as we know earlier, compares two strings or characters. For comparison, the JVM uses their hash codes only. This way of comparison is very faster than comparing each character in the two strings. This hash code format cannot be used by the programmer in coding.
hashCode() vs equals(): About equals() method()
equals() is a method of Object class. This method is not designed to exactly compare the properties of two objects; but designed, to know whether two references refer the same object or not. Many classes override this method for their convenience. String() and System classes has overridden this method to know two objects are same or not.
Following program shows the usage of hashCode() vs equals() methods.
public class Test
public static void main(String args)
Test t1 = new Test();
Test t2 = new Test();
int a = t1.hashCode();
int b = t2.hashCode();
System.out.println("t1 object hash code: " + a);
System.out.println("t2 object hash code: " + b);
System.out.println("t1 and t2 refers the same");
System.out.println("t1 and t2 does not refer the same");
Test t3, t4;
t3 = t1;
t4 = t1;
System.out.println("t3 and t4 refers the same");
System.out.println("t3 and t4 does not refer the same");
Output screenshot onhashCode() vs equals() Example
getClass() method of Object class returns the class for which object t1 belongs. hashCode() method returns the hash code of the object t1. equals() method for t1 and t2 returned false and for t3 and t4 returned true as t3 and t4 refer the same t1 object. Comparing objects with hashcode is known as hashing.
About Hashing and Hashcode
Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.
Hashing is process of converting a string or object into a 32-bit hashcode integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination with equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.