Class overrides equals or hashCode but not both

ID

apex.correctness.override_equals_hashcode

Severity

high

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Api Design

Language

Apex

Description

Reports a class declaring Boolean equals(Object) without Integer hashCode(), or Integer hashCode() without Boolean equals(Object).

Rationale

Set and Map in Apex place an object by its hashCode and only then compare with equals. A class that redefines one of the two breaks that agreement: two instances the code considers equal land in different buckets and both survive in the same Set, or two unequal instances share a bucket and one silently replaces the other as a Map key. The result is a collection whose contains disagrees with == on the same pair of objects, and the deduplication or the lookup that depends on it drops or duplicates records with no error anywhere.

The following code illustrates the pattern detected by this rule:

// FLAGGED: Class overrides equals or hashCode but not both
public class CurrencyAmount {

    public Decimal value;
    public String isoCode;

    public Boolean equals(Object other) {
        if (!(other instanceof CurrencyAmount)) {
            return false;
        }
        CurrencyAmount o = (CurrencyAmount) other;
        return value == o.value && isoCode == o.isoCode;
    }
}

Remediation

Declare both methods and derive them from the same fields: hashCode from exactly the fields equals compares, so equal objects always produce the same hash. Where the identity is a single string or id, returning that field’s own hashCode() is enough.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved