Common equals Implementation Patterns
What you'll learn: You'll master the standard recipe for writing a correct equals method: type check, cast, and field-by-field comparison.
The Standard Recipe
When you override equals, there's a well-established pattern that prevents common mistakes and follows the contract you learned previously. Think of it like following a recipe—each step serves a purpose.
Step 1: Check if it's the Same Object
First, use == to see if you're comparing an object to itself:
if (this == obj) {
return true;
}
This is an optimization: an object is always equal to itself.
Step 2: Check for null and Type Compatibility
Next, verify the object isn't null and is the correct type:
if (obj == null || getClass() != obj.getClass()) {
return false;
}
This prevents NullPointerException and ensures you're comparing apples to apples, not apples to oranges.
Step 3: Cast to the Correct Type
Now it's safe to cast:
Person other = (Person) obj;
You know obj is a Person because you just checked its type.
Step 4: Compare Fields
Finally, compare each field that defines equality:
return age == other.age && name.equals(other.name);
For primitives, use ==. For reference types, use their equals method.
Complete Example
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person other = (Person) obj;
return age == other.age && name.equals(other.name);
}
Key Takeaway: The standard equals pattern follows four steps: same-object check, null/type check, safe cast, then field-by-field comparison using == for primitives and equals for objects.