equals( ) method and hashCode( )

hashCode methods should be compatible with equals methods
  • If two objects are equal, their hashCodes should match
  • a hashCode method should use all instance variables
  • The hashCode method of the Object class uses the memory location of the object, not the contents
Computing Object Hash Codes:
  • You should have a good hashCode method for your own objects to store them efficiently
  • Override hashCode methods in your own classes by combining the hash codes for the instance variables
 public int hashCode()
  int h1 = name.hashCode();
  int h2 = new Double(area).hashCode();
. . .

  • Then combine the hash codes using a prime-number hash multiplier:
  final int HASH_MULTIPLIER = 29;
  int h = HASH_MULTIPLIER * h1 + h2;
  return h;