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;
}
}