This week's book giveaway is in the Testing forum. We're giving away four copies of Data Structures the Fun Way: An Amusing Adventure with Coffee-Filled Examples and have Jeremy Kubica on-line! See this thread for details.
It's not because objects have the same hashcode that these objects are equal. The hashcode() function is made to find an object quickly, not for testing equality. That's where the equals() method is used for. So although it isn't that good to have several different objects with same hashcode (regarding seeking time) it is perfectly legal. Objects that are equal are obliged to have same hashcode.
You should always override both equal and hashcode method if you are using collection that are using hashcode algorithm. equal method is used to check equality of two objects and hashcode method is used to check hashcode of two objects when they are stored in hashcode bucket To check object in hashcode bucket there are two steps 1.to check equality of two objects using equal method 2.to check hashcode using hashcode method When both methods return postive result then object is located in hashcode bucket.If any one of above method will return negative result the object present in hashcode bucket will not be located. This is why both methods are required to override.
"you should always override hashCode( ) when you override equals( ). "
If you override equals and do not override hashcode, then the contract of equal objects having same hashcode will be broken because the hashcode method of java.lang.Object will be invoked and will give different value for each object