See Bloch's Effective Java #9.
But you should start with an initial value (so that subsequent zero values are significant), and combine the fields that apply to the result along with a multiplier so that order is significant (so that similar classes will have much different hashes.)
Also, you will have to treat things like long fields and Strings a little different. e.g., for longs:
(int) (field ^ (field>>>32))
So, this means something like:
@Override public int hashCode() {
int result = 17;
result += name.hashCode() == null ? 0 : name.hashCode();
result = 31 * result + (int) (DoB ^ (DoB >>> 32));
return result;
}
31 is slightly magic, but odd primes can make it easier for the compiler to optimize the math to shift-subtraction. (Or you can do the shift-subtraction yourself, but why not let the compiler do it.)
equalsoverride. You might want to multiply the long by something odd, e.g., 31.hash(a) + hash(b) != hash(a+b). while not exactly easy to do, someone could probably find a completely different SINGLE string that hashes to the same value as your combined hash(a)+hash(b).Longs inDoSalone than there are possible hashes), and it does not have to be. The question should be: is it unique enough?