Overriding hashCode() and equals()


  • equals(), hashCode(), and toString() are public.
  • Override toString() so that System.out.println() or other methods can see something useful, like your object's state.
  • Use == to determine if two reference variables refer to the same object.
  • Use equals() to determine if two objects are meaningfully equivalent.
  • If you don't override equals(), your objects won't be useful hashing keys.
  • If you don't override equals(), different objects can't be considered equal.
  • Strings and wrappers override equals() and make good hashing keys.
  • When overriding equals(), use the instanceof operator to be sure you're evaluating an appropriate class.
  • When overriding equals(), compare the objects' significant attributes.
  • Highlights of the equals() contract:
  • Reflexive: x.equals(x) is true.
  • Symmetric: If x.equals(y) is true, then y.equals(x) must be true.
  • Transitive: If x.equals(y) is true, and y.equals(z) is true, then z.equals(x) is true.
  • Consistent: Multiple calls to x.equals(y) will return the same result.
  • Null: If x is not null, then x.equals(null) is false.
  • If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.
  • If you override equals(), override hashCode().
  • HashMap, HashSet, Hashtable, LinkedHashMap, & LinkedHashSet use hashing.
  • An appropriate hashCode() override sticks to the hashCode() contract.
  • An efficient hashCode() override distributes keys evenly across its buckets.
  • An overridden equals() must be at least as precise as its hashCode() mate.
  • To reiterate: if two objects are equal, their hashcodes must be equal.
  • It's legal for a hashCode() method to return the same value for all instances (although in practice it's very inefficient).
  • Highlights of the hashCode() contract:
  • Consistent: multiple calls to x.hashCode() return the same integer.
  • If x.equals(y) is true, x.hashCode() == y.hashCode() is true.
  • If x.equals(y) is false, then x.hashCode() == y.hashCode() can be either true or false, but false will tend to create better efficiency.
  • transient variables aren't appropriate for equals() and hashCode().