• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating a quality hashcode method  RSS feed

 
David Irwin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All,

I'm trying to develop a quality hashcode method based on Joshua Bloch's "Effective Java Programming" book. I have an object who's equal method depends on two objects: a Double and a Date object. Subsequently, I believe that the hashcode method should create a hashcode based on these two objects as well. What I have so far, and this may not be correct:



I figure I can't just have result = result * 37 + date.hashCode() because might this cause an integer overfill? In look at the JDK5.0 source, I looked at the HashMap.Entry private class's hashcode method:



So...could I so something like this:



My question is this: when you're developing a hashcode based on two or more objects (not integers, doubles, etc.), what's the best way to implement this? Should I follow the example from the JDK source?

Thanks,
Dave
[ June 21, 2006: Message edited by: David Irwin ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd use Bloch's advice myself. If it overflows it overflows. We're just trying to get a number that corresponds to the data (and is unlikely to produce false duplicates in a particular set of data.) We don't have to be able to reverse or decode it, so some information loss through overflow is not a big deal. Is it?
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave, why do you think integer overflow is a problem? You're not going to get an error or anything like that. The most important thing is that equal instances have equal hash codes. The less collision you have between unequal instances the better, but as long as they're equal that's just a matter of performance in hash-based collections and so forth that gets marginal at a certain point. I say follow Bloch's template and don't worry about it.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd advice to simply use the the HashCodeBuilder from jakarta commons lang.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!