Skip to content

Instantly share code, notes, and snippets.

@xilin
Created January 24, 2014 07:47
Show Gist options
  • Save xilin/8593614 to your computer and use it in GitHub Desktop.
Save xilin/8593614 to your computer and use it in GitHub Desktop.
// A for nearly all cases reasonable good implementation was proposed in Josh Bloch's "Effective Java" in item 8. The best thing is to look it up there because the author explains there why the approach is good.
// A short version:
// 1) Create a int result and assign a non-zero value.
// 2) For every field tested in the equals-Method, calculate a hash code c by:
// If the field f is a boolean: calculate (f ? 0 : 1);
// If the field f is a byte, char, short or int: calculate (int)f;
// If the field f is a long: calculate (int)(f ^ (f >>> 32));
// If the field f is a float: calculate Float.floatToIntBits(f);
// If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;
// If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
// If the field f is an array: See every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.
// 3) Combine the hash value c with result with:
// result = 37 * result + c
// 4) Return result
// This should result in a proper distribution of hash values for most use situations.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_title== null) ? 0 : _title.hashCode());
result = prime * result + _year;
result = prime * result + (int) (Double.doubleToLongBits(_rating) ^ (Double.doubleToLongBits(_rating) >>> 32));
result = prime * result + (int) (_numberOfVotes ^ (_numberOfVotes >>> 32));
result = prime * result + ((_categories== null) ? 0 : _categories.hashCode());
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment