hashCode()

Hi!Why do we need to override equals() when we override hashCode()?Thanks!
[95 byte] By [java_bluesa] at [2007-10-2 21:55:41]
# 1
hiequals()hashcode()toString()All These method are defined in Object class.So these method are override in the sublassObject class are implicitly in class.
delhia at 2007-7-14 1:11:43 > top of Java-index,Java Essentials,Java Programming...
# 2
> Hi!> > Why do we need to override equals() when we override> hashCode()?> > Thanks!See the javadoc for the methods they do explain why.Kaj
kajbja at 2007-7-14 1:11:43 > top of Java-index,Java Essentials,Java Programming...
# 3

You don't. It's the other way around. If you override equals, you should override hashCode.

See the contract specified in Object.

[url]

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html

[/url]

If you override equals so that two distinct objects can be considered equal values and thus equals returns true for them, then you have to ensure that hashCode also returns the same value for both objects.

If you override equals but not hashCode, you cannot maintain this contract. But you can override hashCode alone (for example, make it always return 13) without breaking the contract.

The reason for this is the way Hashtables work; if you override equals but not hashCode, they won't; if you override hashCode as I said above, everything will work but it will be slow, very slow indeed.

Lokoa at 2007-7-14 1:11:43 > top of Java-index,Java Essentials,Java Programming...
# 4
Thanks a ton !
java_bluesa at 2007-7-14 1:11:43 > top of Java-index,Java Essentials,Java Programming...