Java and Spring Level 1 This level · 91 of 105
Easy java spring

Two Employee objects with identical data compared; equals() never overridden?

The 30 second answer

Object.equals is identity, so two different instances with the same fields are not equal. A HashSet keeps both, contains on a copy returns false, and map lookups with a newly built key miss. You must override equals and hashCode together, or use a record, which generates both from its components.

Could you say this in an interview?

Object.equals is identity (this == obj), so e1.equals(e2) is false; HashSet keeps both, list.contains(copy) fails, map lookups with a new key miss. Override equals and hashCode together (contract: equal objects ⇒ equal hash codes), or use a record, which generates both from components.

record Employee(long id, String name) {} // equals and hashCode from components
Sources (2)
  1. Object.equals / hashCodedocs.oracle.com
  2. Recorddocs.oracle.com
Previous
Next