Record With Array Component Missing Overrides

ID

java.equals_method_overridden_records_containing

Severity

high

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

best-practice, reliability

Description

Reports a record with an array-typed (or varargs) component that does not override equals, hashCode and toString.

Rationale

A record’s generated equals, hashCode and toString compare and print components by value — except array components, which they treat by reference. Two records holding arrays with the same elements compare unequal, hashCode() varies between otherwise-identical instances, and toString() prints something like [I@1a2b3c instead of the array’s content.

// Bad -- scores is compared and printed by reference
record Measurement(String subject, int[] scores) {
}

Remediation

Override equals, hashCode and toString to delegate to java.util.Arrays for every array component.

// Good -- array content drives equality, hashing and printing
record Measurement(String subject, int[] scores) {
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Measurement)) {
            return false;
        }
        Measurement other = (Measurement) o;
        return subject.equals(other.subject) && Arrays.equals(scores, other.scores);
    }

    @Override
    public int hashCode() {
        return 31 * subject.hashCode() + Arrays.hashCode(scores);
    }

    @Override
    public String toString() {
        return subject + "=" + Arrays.toString(scores);
    }
}

© 2026 Xygeni. All rights reserved