aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashcode() 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 "hashcode()" Watch "hashcode()" New topic
Author

hashcode()

Kaz Yosh
Ranch Hand

Joined: May 22, 2003
Posts: 63
Hi all,
can anybody explain this?
Given the following class, which are correct implementations of the hashCode() method?

[ May 29, 2003: Message edited by: Thomas Paul ]

"If anything can go wrong, it will"
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Two ValuePair objects are equal if they contain the same valuer in their ints. (a == a and b == b) or (a == b and b == a)
So the hashCode method must return an int so that equal objects have equal hashcodes. So a possible valid implementation might be a+b. Returning either a or b would not be valid.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Kaz Yosh
Ranch Hand

Joined: May 22, 2003
Posts: 63
Can you explain a bit more about hashcode?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
There is an article in the JavaRanch newsletter about the hashCode method.
Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
I've recently read a chapter on this. My understanding with implementing hashCode() is that you take a look at the equals method and see which member variables are being used to compare the "value" of the instance of the class, and then create a hashCode implementation like: a+b.
Now, I've been out of college for about 4 years, so my CS knowledge is not quite as sharp, but I was surpised to learn that a valid hashcode could also just be a constant, just "return 123;", but this would not be "efficient" because then every object would have the same hashcode, and I guess that this means when hashing your objects you won't get a good distribution in a Hashtable.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: hashcode()