I have an object whose primary identity consists of a combination of an Enum type and a long. What hashcode generation logic should I use for efficient fetching of the object from maps or some other functioning.
Almost the same approach: take the previous hash code, multiply by a prime number, and add a new part to it. The only difference is that my initial value is 0 instead of a prime number (7). 1 is also a sometimes used initial value.
The usual "rules" for calculating hash code parts:
- objects: (object == null ? 0 : object.hashCode())
- byte, char, short, int: the value itself
- float: Float.floatToIntBits(value)
- long: (int)(value ^ (value >>> 32)) (i.e. what Matthew already posted)
- double: Double.doubleToLongBits(value) to convert to long, then the long to hashCode computation
- boolean: use Boolean.valueOf(value).hashCode(). This (currently) returns 1231 for true, 1237 for false. Because Boolean.valueOf(boolean) always returns one of the two static final fields it won't add any memory usage.
Assuming you only have those two fields. I can't remember whether ^ has a higher precedence than >> or vice versa.
Unary > Arithmetic > Comparison > Bitwise > Logical > Ternary > Assignment
These are broad categories I have memorized in order to remember the precedence.
Note that bitwise shifts are considered arithmetic, so they trump xor operations.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Joined: Oct 13, 2005
You are right; >> has a higher precedence than ^ so one of my pairs of () is redundant.
Joined: Oct 20, 2010
It seems I will have to read some book before I get to fully understand all your replies. Meanwhile, I will follow Matthew's suggestion and let the netbeans produce the hashCode and equals. Here is the code generated by Netbeans. In the code the phoneType is the enum and donorId is long. I hope this is efficient.
Wait what? That can't be right. donor is definitely not a long; it's being used as an Object (comparing against null, calling methods on it, etc). Is it perhaps a Long?
Joined: Oct 20, 2010
Sorry for being late to respond. Donor is definitely an object as you guessed, but it has a long id as donorId. The hashcode for it is also generated by netbeans. So in short the Phone Entity has effectively an Identity that is composed of PhoneType and DonorId (mapped as Donor in hibernate). The hashcode generation logic for Phone entity refers to the hashcode of Donor entity. So I think this must work correctly.