File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode()

 
Kaz Yosh
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kaz Yosh
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you explain a bit more about hashcode?
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is an article in the JavaRanch newsletter about the hashCode method.
 
Brian Joseph
Ranch Hand
Posts: 160
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic