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 ]
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?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
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.
I'd advice to simply use the the HashCodeBuilder from jakarta commons lang.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Talk sense to a fool and he calls you foolish. -Euripides A foolish tiny ad:
SKIP - a book about connecting industrious people with elderly land owners