- hashCode() and equals() are methods of Object class.
- Default implementations
- hashCode() – returns the address of the object
- equals() – checks if the reference of current and passed object is same. Same as equality operator ==
- Overwriting equals methods provides shallow comparison of the objects
- equals will only take java object and not primitive datatypes
- if null is passed as str.equals(null). it will return false and not NPE
- If 2 objects have same hashcode it does not guarantee that they are equal
- String class caches its hashcode() as it is immutable
Contract of equals() and hashCode() method
- Reflexive – Object must be equal to itself. s1.equals(s1) == true;
- Symmetric – if s1.equals(s2) then s2.equals(s1) should also be true. Also custom class should never be equals to Java’s in-built classes
- Transitive – if s1.equals(s2) and s2.equals(s3) then s1.equals(s3) should also be true
- Consistent- if s1.equals(s2) then they should remain equal until one of them is modified. Likewise if they are not equals then they should remain unequal until they are modified.’
- Null Comparison- s1.equals(null) should always return null and not NPE.
- Equals & Hashcode relationship – If s1.equals(s2) then s1.hashCode() == s2.hashCode(); But if 2 objects hashcode is same it does not mean that those 2 objects as same
- hashCode() is an hash of any object. Always use the same data that is used in comparison in equals() method for generating hashCode().