This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
iam confused about equals() and hashCode() method, which has to be over ridden when comparision is made among to collection objects. if two objects are equal their hshcodes must be equal, is reverse true. please help me,
Thanks in Advance [ February 09, 2008: Message edited by: gobburi saikrishna ]
just remember that while using "hash collections", both hashCode and equals are used to help fiding the right "thing".
hashCode is used to put things into the "box", while equals is used to search in the "box".
If two objects have different hashCode, they will be in different "boxes", and will never be found no matter their equals method look like. So "if two objects are equal their hashcodes must be equal" or you cannot find them once you lost their original reference variable.
If two objects have equals hashCode, they will be in the same box, and the equals method is still able to find them, because they are in the same "box". So "if two objects are equal their hashcodes don't necessary needs to be equal".
Originally posted by naga sandeep: ...two objects are said to be equal if their hashcodes are equal...
If two objects are equal, then their hashcodes must be equal. But two unequal objects can certainly have equal hashcodes. In other words, we can not say that two objects are equal if their hashcodes are equal.
In the table on p. 534 of K&B, look at the row for "x.equals(y) == false." These objects not equal, but in the third column it says, "No hashCode() requirements." So one possibility is that these unequal objects might have the same hashCode.
For details on the hashCode contract, see the API documentation of the hashCode method in java.lang.Object. [ February 10, 2008: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
because even though they are similar, they are different. that's the whole idea...
i can write my code using one of the collection classes. OTHER people then use a common API to interact with my code.
if 6 months later i realize that while i had been using a "Foo" class, perhaps "Bar" would work better. I can change MY code, but since it uses the same API, all those OTHER coders don't have to change a thing.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors