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.
The hashCode() method is used by collection classes such as HashSet and HashMap. It will be called by those collection classes when you add or lookup objects. If you want to know when it's called on your object, then add for example a System.out.println(...) call in your hashCode() method:
That hashCode method is called on the "K" objects in a Map whenever it is used as a Key for "put" or "get" or it is sought with "containsKey." I don't think it is used for "add" or "equals" which are not actually Map methods.
Go into your Java installation folder, find a file called src.zip, unzip it, go into the java folder, then util, then find a class which implements Map, eg HashMap. You can read the code and see how the hash code is used.
Joined: May 29, 2008
Thanks to both of you, just one last doubt ; i found it weird the hasCode method gets called even if i print the HashCode object .
Whenever you print any object , the objects toString() method gets called , which , in turn prints some meaningful information explaining it . But if that class dosent override toString() method, the object simply print its hash code value !