Equals Without Instanceof

ID

java.equals_use_instanceof

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Java

Tags

CWE:480, best-practice

Description

Reports equals(Object) methods that do not contain an instanceof check.

Rationale

The equals contract requires that the method must never throw — it should return false for arguments of incompatible types. Without an instanceof check, a direct cast to the expected type will throw ClassCastException when the argument is the wrong type or null. The instanceof operator safely handles both cases: it returns false for null and for non-matching types.

// Bad -- no instanceof, will throw on wrong type
public boolean equals(Object o) {
    MyClass other = (MyClass) o;
    return this.value == other.value;
}

Remediation

Add an instanceof check before the cast:

// Good -- instanceof guards the cast
public boolean equals(Object o) {
    if (!(o instanceof MyClass)) {
        return false;
    }
    MyClass other = (MyClass) o;
    return this.value == other.value;
}