This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
jose chiramal wrote:when do we override equals and hashcode nmethods ? What happens if we dont override them in our class ? Can we overload them ? Whats the relationship between the two ie. equals and hashcode.
You override the equals() and hashCode() methods, if you intend to use your objects in any hashing collection. If you don't intend to use them, in a hashing collection, then I guess nothng will happen.
See the JavaDoc for the java.lang.Object class for some details about the hashcode/equals contract.
In addition to what Henry said if you override hashcode and equals, you can define the equality constraint of the fields of the object and hence it will be possible to compare two objects directly.
Thanks and Regards,
Just to add on, if two objects are equal as per equals(), they need to have the same hashcode values so that they can be retrieved from collections. So if you override equals(), you also need to override hashcode().
However, if two objects are not equal as per equals(), their hashcodes may or may not be the same. This totally depends on the hashing algorithm you are using.