Ebay Interview Question
Software Engineer / DevelopersVery right .... Thanks ... another one of the same types could be why do we need to override the hashcode function if we override the equals method for object class.
as explained by SB hasCode() is used for the hashing function, so lesser the time while searching some element.
When an object is checked for equality first hasCode value is checked and if it is not equal then only equals method is called.
Consider a situation when you have not overridden hasdcode() method.
Employee e1 : name= "abc"
Employee e2: name= "abc"
Both are logically equal, so hashCode() should return the same value as per the hashCode and equals method contract.
If you do not override the hashCode method, then it will return 2 different value when 2 objects are compared.
And even if above object are equal, it will return false.
hashcode() is mainly used for defining hash function as equals() is called only when collision occurs. So, having a good hashfunction will save you time by not calling equals()
- Messi February 17, 2011