• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

hashcode()

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can you explain a bit more about hashcode?
 
Thomas Paul
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is an article in the JavaRanch newsletter about the hashCode method.
 
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic