K5kC LogoK5kC | Code & More
Computer Science
AlgorithmsJavaProgramming LanguagesDatabaseSystem Design
Problems
Blind 75Algo KernelDifficulty: EasyDifficulty: MediumDifficulty: Hard
Videos
Projects
AndroidData ScienceComputer VisionSimulations
Tools
UUID GeneratorCode Formatter
Search⌘K
Computer Science
Java
Core Java
Object-Oriented Programming in Java
The Object Class and Its Methods
Java equals() Method Explained

Core Java

Overview
OverviewEquality in Java: == and equalsequals() Method Explainedequals() and hashCode() Contract for ObjecthashCode() ExplainedWrapper Caching and String PooltoString() Explained
Encapsulation in Java: Hiding Data and Protecting Invariants
Encapsulation vs AbstractionImmutable ClassesRecords
Computer Science
Java
Core Java
Object-Oriented Programming in Java
The Object Class and Its Methods
Java equals() Method Explained

Java equals() Method Explained

  • Why override equals?
  • The contract
  • Writing equals step by step
  • Worked example: Point
  • Naive version 1: not really overriding equals
  • Naive version 2: forgetting hashCode
  • Naive version 3: mutable fields in the hash
  • A sound implementation
  • Subclasses
  • Should a subclass instance equal a superclass instance?
  • A subclass that adds state
  • The careful way: canEqual
  • The easy way
  • Or use composition
  • Best practices
  • When not to override
  • In practice
  • Testing
  • Together with hashCode()
← PreviousEquality in Java: == and equalsNext →Java equals() and hashCode() Contract for Object
PrivacyDisclaimerReport an IssueAbout

© 2026 K5kC | Code & More. All rights reserved.

चरैवेति चरैवेति | Keep moving on