Skip to content

Array components

pawel_labaj edited this page Apr 12, 2023 · 7 revisions

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. See more information at java:S6218 rule.

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

Example interface and generated record

Here's an example interface:

import pl.com.labaj.autorecord.AutoRecord;

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

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

import static java.util.Objects.hash;
import static java.util.Objects.requireNonNull;

import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.processing.Generated;
import pl.com.labaj.autorecord.GeneratedWithAutoRecord;

@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) +
                "]";
    }
}
Clone this wiki locally