intermediate~3h

equals(), hashCode(), and the Contracts That Hold Collections Together

The formal equals()/hashCode() contract, why overriding one without the other quietly breaks every hash-based collection, and how Comparable and Comparator give objects two independent, legitimate notions of ordering.

Learning objectives

  • State the formal equals() contract (reflexive, symmetric, transitive, consistent, null-safe) in your own words
  • Explain precisely why hashCode() must be overridden whenever equals() is, and what breaks if it isn't
  • Implement equals()/hashCode() correctly for a custom class, including with inheritance
  • Distinguish Comparable's single natural ordering from Comparator's unlimited external orderings
  • Recognize the most common bugs caused by violating these contracts in real code

This is a Pro chapter

Sign in, then upgrade to Pro or Power to unlock this and the full Core Java Mastery library.

equals(), hashCode(), and the Contracts That Hold Collections Together

Next Step

Continue to Iterators, Fail-Fast Traversal, and the Collections/Arrays Utility Belt →← Back to all Java Collections Framework chapters