How to Design hashCode method


Effective Java 2nd EditionのItem 9に"Always override hashCode when you override equals"という項目があるが、ここで説明されているhashCodeメソッドの実装方法はいざというときにリモートから参照できるべきだと思ったので書いておこう。

stackoverflowのHash Code implementationにも似たようなことが書いてあったのでまずはコピペ。

  1. Create a int result and assign a non-zero value, ex. 17.
  1. 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 is a null referenence.
  • 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.
  1. Combine the hash value c with result with:
  result = 37 * result + c
  1. Return result


例えば、areaCode, prefix, lineNumberから成るPhoneNumberクラスのhashCodeメソッドは以下のようになる。

@Override
public int hashCode() {
  int result = 17;
  result = 31 * result + areaCode;
  result = 31 * result + prefix;
  result = 31 * result + lineNumber;
  return result;
}