File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes why should i need to override hashcode when i override equals method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "why should i need to override hashcode when i override equals method" Watch "why should i need to override hashcode when i override equals method" New topic
Author

why should i need to override hashcode when i override equals method

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
hi, why should i override hashcode method when i override equals method?

and can any one provide me a program how it really needs ?
thanks in advance


A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14685
    
  16

Because two instances returning different hashcodes won't be equal.
A foolish example. equals() always returns true, but "c" is not found.



[My Blog]
All roads lead to JavaRanch
Carl Trusiak
Sheriff

Joined: Jun 13, 2000
Posts: 3340
There are three methods that are closely related, each may be used by different Collection type to determine equality.
equals
hashCode
compareTo (For Sorted Collection, you must implement the Comparable innerface)

For your object to function in the various Collections as documented, the following rule should be followed.

hashCode will return the same value and compareTo will return 0 when equals returns true

If your objects will never participate in hash based collections or sorted collections, it's not necessary to follow that rule however, it will either limit what you can do or result in unexpected results.

I've seen this in one project. TreeSet is documented to contain one and one one of any object which equas is true. However, following the rule above, it actually uses compareTo returning 0 to do this. On this job someone wrote compareTo in a way inconsistant with the rule and as a result, doubles where going in and some objects where apparently randomly being excluded from the TreeSet.

Unless you have a large complelling reason to not follow the rules, I recommend you make it a habit. And any time you diviate prepare for some unexpected results.


I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: why should i need to override hashcode when i override equals method
 
Similar Threads
Overriding hashCode()
hashcode
A question about hashCode
hashing
Doubt in overriding hashcode ...