what's hashCode() method?

Share

in the API docs of the equals() method in Object class it's written:

"Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes."

i've read the hashCode() API but i couldn't understand what exactly does this method do.

can anyone help?

briefly... for each objects a and b if a.equals(b) is true then a.hashCode() == b.hashCode() must be always true. This is why you need to override the hashCode method whenever you override the equals.
However if a.equals(b) is false , a.hashCode() == b.hashCode() may be or may not be true. It is totally up to you! \\
That is, if you have some business object, you may override the equals method to compare its member variables one by one. But you would choose to return equal hash code only if their key (business key, unique key or whatever you want to call it) values are equal. \\
This is actually an important thing that you need to care about if you are using Hibernate and/or hash based collections. Read more about that in [this chapter of Effective java || http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf ]

thank you. this revealed the picture to me a bit. but i couldn't access the link you provided. i got a message "access denied, you're not authorized...".

I donno what happened to the link but you would find it easily if you google that (Effective java hashCode). It was chapter 3 AFAIR

i could find it.

thank you