Non-Null Annotation on equals() Parameter
ID |
java.equals_method_params_marked_nonnull |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability |
Description
Reports an equals(Object) override whose parameter is annotated @Nonnull, @NonNull or @NotNull (from any package).
Rationale
Object.equals(Object) is documented to accept null and return false for it: x.equals(null) must never throw. Marking the parameter non-null asserts the opposite, which is misleading to readers and to any static analysis or IDE inspection that trusts the annotation — and it invites a caller to skip the null check that the override itself may still need.
// Bad -- parameter annotation contradicts what equals() must accept
public class Invoice {
@Override
public boolean equals(@Nonnull Object other) {
return other instanceof Invoice && id == ((Invoice) other).id;
}
}
Remediation
Drop the non-null annotation from the parameter and let the method body handle null explicitly, as the contract requires.
// Good
public class Invoice {
@Override
public boolean equals(Object other) {
if (!(other instanceof Invoice)) {
return false;
}
return id == ((Invoice) other).id;
}
}