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.
Correct me if I'm wrong...
SCJP 5.0, SCEA part I
Steven Gao Song
Joined: Oct 02, 2006
Thank you, Bram
I made a mistake. I was always thinking that the method equals() just use hashCode() to judge whether two references are sharing the same object or not.
But, in "Thinking in Java 3rd", the author says "you should always override hashCode( ) when you override equals( ). " Who can tell me the relationship between the two methods?
Joined: Feb 07, 2005
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