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

  • equals that always returns true makes every object equal to every other object, breaking symmetry across distinct instances and poisoning collection behaviour — HashSet collapses all entries, Map keys collide.

  • equals that always returns false violates reflexivity — x.equals(x) must be true, 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;
}