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 |
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;
}