Skip to content

Array components

pawel_labaj edited this page Aug 2, 2023 · 7 revisions

What is the issue

In records, the default behavior of the equals() method is to check the equality by field values. This works well for primitive fields or fields whose type overrides equals(), but this behavior doesn’t work as expected for array fields. Look for more information at java:S6218 Sonar rule.

That's why, when there is an array recordComponent in generated record, AutoRecord generates hashCode(), equals() and toString() methods.

Example interface and generated record

Here's an example interface:

@AutoRecord
interface Person {
    String name();
    String[] permissions();
}

Here's the corresponding generated record that demonstrates array recordComponent handling:

@Generated("pl.com.labaj.autorecord.AutoRecord")
@GeneratedWithAutoRecord
record PersonRecord(String name, String[] permissions) implements Person {
    PersonRecord {
        requireNonNull(name, "name must not be null");
        requireNonNull(permissions, "permissions must not be null");
    }

    @Override
    public int hashCode() {
        return hash(name, Arrays.hashCode(permissions));
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (!(other instanceof PersonRecord)) {
            return false;
        }

        var otherRecord = (PersonRecord) other;
        return Objects.equals(name, otherRecord.name)
                && Arrays.equals(permissions, otherRecord.permissions);
    }

    public String toString() {
        return "PersonRecord[" +
                "name = " + name + ", " +
                "permissions = " + Arrays.toString(permissions) +
                "]";
    }
}