File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes correct hashCode( ) method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "correct hashCode( ) method" Watch "correct hashCode( ) method" New topic
Author

correct hashCode( ) method

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
Ruels for correct implementation of hashCode() method :

1] if two object returning true with equals() method , then they should return same int with hashCode() method .

2] But the vice versa is not true . I mean two object may have same hash code but not returning true with equals() method .

Is this right ???
Ray Stojonic
Ranch Hand

Joined: Aug 08, 2003
Posts: 326
Originally posted by rathi ji:
Is this right ???

Yes
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

I mean two object may have same hash code but not returning true with equals() method .


Not only is it right, it is impossible for it to be wrong.
That is, if I created Integer.MAX_VALUE + 1 unique (equals returns false) instances your class, I am guaranteed a hash code collision.

In practice, it is quite simple to create a hash code collision.
I wrote a small application once to demonstrate that generating random 5 character Strings results in a collision about 3 times per second on my development machine. I wrote it because some twit was trying to use a String as a switch argument and claimed that "it works" if you call hashCode. This is despite the fact that the switch/case construct is evil in itself.
[ January 27, 2005: Message edited by: Tony Morris ]

Tony Morris
Java Q&A (FAQ, Trivia)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: correct hashCode( ) method