equals() Always Returns a Constant
ID |
java.equals_always_constant |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports equals(Object) methods where every return statement yields the same
boolean literal (true or false). Both forms violate the Object.equals
contract.
Rationale
-
equalsthat always returnstruemakes every object equal to every other object, breaking symmetry across distinct instances and poisoning collection behaviour —HashSetcollapses all entries,Mapkeys collide. -
equalsthat always returnsfalseviolates reflexivity —x.equals(x)must betrue, which any cache, set, or map lookup relies on.
@Override
public boolean equals(Object obj) {
return true; // Bug: all objects appear equal
}
@Override
public boolean equals(Object obj) {
return false; // Bug: x.equals(x) is false
}
Remediation
Implement a proper equality check that compares the relevant fields.
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof MyClass)) return false;
return this.id == ((MyClass) obj).id;
}