BrianMc1958
asked on
Making a hash of hashCode
Dear Experts,
I have some simple data beans that need to override hashCode. One of you Experts gave me a simple hasCode example a while back, which I implemented like this:
public int hashCode()
{
int hash = 17;
hash = hash * 37 + bankID;
hash = hash * 37 + applicationCode;
hash = hash * 37 + (int) accountNbr; // this is a long
return hash;
}
My problem is, at least on this example, accountNbr is a long, not an int. (It a ten-byte numeric.) So I'm obviously losing some precision here.
My question is: Is that a little bit bad, or just plain wrong? (If it just means less-than-optimal sorting, for instance, that's OK for my purposes.)
And if it's just plain wrong, what do I do? hashCode needs to return an int, right?
Thanks again...
BrianMc1958
I have some simple data beans that need to override hashCode. One of you Experts gave me a simple hasCode example a while back, which I implemented like this:
public int hashCode()
{
int hash = 17;
hash = hash * 37 + bankID;
hash = hash * 37 + applicationCode;
hash = hash * 37 + (int) accountNbr; // this is a long
return hash;
}
My problem is, at least on this example, accountNbr is a long, not an int. (It a ten-byte numeric.) So I'm obviously losing some precision here.
My question is: Is that a little bit bad, or just plain wrong? (If it just means less-than-optimal sorting, for instance, that's OK for my purposes.)
And if it's just plain wrong, what do I do? hashCode needs to return an int, right?
Thanks again...
BrianMc1958
If you are using Java5, you could try using a prebuilt hashcode function instead.
import java.util.Arrays;
public int hashCode()
{
return Arrays.hashCode( new long[] {bankID, applicationCode, accountNbr } );
}
I don't think your method is wrong. Hashcode generally isn't used for sorting, it is for hash maps and the like though.
import java.util.Arrays;
public int hashCode()
{
return Arrays.hashCode( new long[] {bankID, applicationCode, accountNbr } );
}
I don't think your method is wrong. Hashcode generally isn't used for sorting, it is for hash maps and the like though.
ASKER
Actually, the whole hashCode thing is still something of a mystery to me. When I mentioned sorting, it was with hash maps in mind. My vague understanding is that the hashCode result (as opposed the the "equals" result) does not need to be unique for all objects. It's one of the few times in our profession where close is good enough. Is that correct?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Actually, you've answered my question. I shouldn't have mentioned sorting in the first place. I just think of hashing as being like sorting, which is off the point here. In my case, a collision will occur very rarely, so it looks like I'm OK.
Thanks a lot!
--BrianMc1958.
Thanks a lot!
--BrianMc1958.
ASKER