equals() is a method for comparing the content of objects, while hashCode() is a method for checking the identity of objects. When overriding these methods, it's best practice to use them together to maintain equivalence comparisons and hash code consistency.
Hash data structures use hashCode() to determine object identity, and overriding both equals() and hashCode() is crucial to prevent hash code collisions and errors.
The correct use of equals() and hashCode() is important for improving efficiency and accuracy when comparing objects and using hash-based data structures.
equals()
equals() compares whether the contents of objects are the same. It is often called equality comparison. If equals() is not overridden, it internally behaves like ==, resulting in identity comparison. Therefore, if you want to properly compare objects for equality, you must use equals().
hashCode()
hashCode() checks if two objects are the same object. It performs the same identity comparison as ==, but the hashCode() method returns a unique integer value for the object during runtime. Generally, it returns the memory address of the object stored in the Heap.
This method has the native keyword attached to it. This keyword is used when using languages developed in languages other than Java in Java.
What is Hash?
Hashing refers to the process of using a hash function to generate a fixed-size output value from a variable-size input value. The value obtained through hashing is called a hash code.
equals() and hashCode()
Since identical objects must have the same memory address, it is self-evident that identical objects must have the same hash code. Therefore, it is advisable to override hashCode() along with equals() to ensure the same hash code.
Hash Data Structure
Let's insert two equivalent objects into the HashSet data structure as shown above. If we print the size of the Set, it will be 2. Why is that?
This is because hash-based data structures use hashCode() to determine the key. In other words, before comparing whether objects are identical, it compares whether the hash codes of the two objects are the same and then determines if the two objects are equal. If hashCode() is not overridden, it uses the hashCode() of Object, so the memory address where each object is stored is returned. Therefore, it's good to override hashCode() as well as equals() for cases where hash data structures are used.
Hash-based data structures use hashCode() to determine the key. That is, before comparing whether objects are the same, it compares whether the hash codes of the two objects are the same, and then determines whether the two objects are equal. If hashCode() is not overridden, it uses the hashCode() of Object, so the memory address where each object is stored is returned. Therefore, it's a good practice to override hashCode() along with equals() when using hash data structures.