Non-Standard equals() Signature
ID |
java.equals_signature_correct |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:581, reliability |
Description
Reports equals() methods whose signature does not match the standard public boolean equals(Object).
Rationale
To properly override Object.equals, the method must be public, return boolean, and accept a single parameter of type Object. A method with a narrower parameter type (e.g., equals(String)) overloads rather than overrides equals, so collections and framework code calling equals(Object) will still use the default identity comparison.
// Bad -- overloads instead of overriding
public class User {
public boolean equals(User other) { // wrong parameter type
return this.id == other.id;
}
}
Remediation
Change the signature to public boolean equals(Object) and add @Override to let the compiler enforce correctness.
// Good
public class User {
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof User)) return false;
return this.id == ((User) other).id;
}
}