A real JDK 23 run: a record holding an array fails equals, hashCode, HashSet lookups and toString, and leaks its state through the accessor. Two fixes and when to use each.
A record that looks like a value and is not
Java records are meant to be transparent carriers of data. Declare the components, and the compiler generates a canonical constructor, accessors, equals, hashCode and toString. For a record of strings and numbers, that is exactly what you want: two records with the same component values are equal, hash the same and print the same.
Put an array in a record and every one of those generated members does something else. The array is compared by reference, hashed by identity and printed as a type name and a hash code. The accessor hands out the array itself, so a caller can change the record's contents after it was built. None of this is a bug in the compiler; it is what the specification says. It is still a common source of real defects, because the record syntax suggests value semantics that the array does not have.
This guide shows each effect with a real run on Java 23.0.2, explains where the behaviour comes from, and gives two fixes with their tradeoffs. The example is a return batch for a help-desk case at the fictional Belgavi's Book Store: a case id and the ISBNs of the books being returned.
The naive record
public record ReturnBatch(String caseId, String[] isbns) {}The example creates two batches for CASE-6101 from two separate arrays with the same two ISBNs, then asks the generated members about them. The output of java RecordArrays:
generated equals on equal contents: false
generated hashCode equal: false
HashSet.contains(b): false
toString: ReturnBatch[caseId=CASE-6101, isbns=[Ljava.lang.String;@7291c18f]
after writing through the accessor: 9789999999999Every line is a separate problem in production code.
equalsreturns false for two batches with the same contents. A deduplication step that compares batches never finds a duplicate.hashCodediffers, so aHashSetor aHashMapkey lookup fails. The example puts one batch in a set and asks whether the set contains the other; it says no.toStringprints[Ljava.lang.String;@7291c18f. Logs and error messages show an identity string instead of the ISBNs, so a support engineer reading a log cannot see which books were in the batch.- Writing through the accessor,
a.isbns()[0] = "9789999999999", changes the record. Anything that held the record, such as a cache or a map key, now holds different data from what it stored.
There is one more, less visible: the canonical constructor stores the caller's array. If the caller later reuses or edits that array, the record changes underneath every holder.
Why the generated members behave this way
The Java Language Specification defines the implicitly declared members of a record class in section 8.10. The generated equals compares each component: for a reference-typed component, equality is as if by Objects.equals. For an array, Objects.equals calls the array's own equals, which is the one inherited from Object: reference identity. The generated hashCode is derived from the components' hash codes in the same way, and an array's hashCode is its identity hash. The generated toString uses each component's toString, which for arrays is the type descriptor and identity hash.
The java.lang.Record documentation states the contract that makes this unavoidable: a record's equals must agree with the component accessors, so that a record copied from its own components is equal to the original. The compiler cannot switch to Arrays.equals for array components without changing what equality means for every record.
JEP 395, which made records a standard feature in Java 16, describes records as shallowly immutable. The fields are final, so the reference cannot change, but the object a field refers to can. An array is the most common case where that shallowness shows.
Fix one: defensive copies and explicit members
If the component must be an array, for example because a library API expects one or because the batch is large and primitive, take ownership of it and override the members that depend on contents:
public record SafeReturnBatch(String caseId, String[] isbns) {
public SafeReturnBatch {
Objects.requireNonNull(caseId, "caseId");
isbns = isbns.clone(); // the caller's array can change later
}
@Override public String[] isbns() { return isbns.clone(); }
@Override public boolean equals(Object o) {
return o instanceof SafeReturnBatch other && caseId.equals(other.caseId) && Arrays.equals(isbns, other.isbns);
}
@Override public int hashCode() { return 31 * caseId.hashCode() + Arrays.hashCode(isbns); }
@Override public String toString() { return "SafeReturnBatch[caseId=" + caseId + ", isbns=" + Arrays.toString(isbns) + "]"; }
}The compact constructor copies the input, and the accessor returns a copy, so neither the creator nor a reader can change the stored array. equals, hashCode and toString use the Arrays helpers, which work on contents. The run now prints safe equals: true, safe hash equal: true, writing through the accessor leaves the record at 9780000000017, and toString lists both ISBNs.
The cost is that you are now maintaining by hand exactly the members records were supposed to generate. Add a component and forget to update equals, and the bug is back in a different form. Copying also costs an allocation per access, which matters only for large arrays read in hot loops.
For arrays of mutable objects, clone copies only the array, not the elements. Arrays.deepEquals and Arrays.deepHashCode handle nested arrays, but nothing generic makes arbitrary element objects immutable.
Fix two: use an unmodifiable List
Most of the time, the simpler fix is not to use an array at all:
public record ListReturnBatch(String caseId, List<String> isbns) {
public ListReturnBatch { isbns = List.copyOf(isbns); }
}List defines equals and hashCode by contents, and its toString lists the elements, so the generated record members are already correct. List.copyOf returns an unmodifiable list: it copies a mutable input, and a caller who tries to add or set an element gets an UnsupportedOperationException. The example builds one batch from Arrays.asList and one from List.of, and the generated equals reports them equal.
Two details to know. List.copyOf rejects null elements with a NullPointerException, which for ISBNs is a feature. And it may return its argument unchanged if that argument is already an unmodifiable list, so the copy is cheap when callers already pass immutable lists.
Choosing between them
Use a List component by default. It keeps the record short, keeps the generated members correct, and makes the immutability visible in the type. Use an array with explicit members only when an array is required: a primitive array for a large numeric payload where boxing would hurt, or an interface that takes and returns arrays. In that case, write tests for equals, hashCode and the accessor, because the compiler no longer protects you.
Static analysis can catch the naive version. Check whether the analyser your build already uses has a rule for array record components; if it does, enabling it is cheaper than finding the problem in a cache, and if it does not, a test that compares two records built from separate but equal arrays does the same job.
Failure modes this causes in real systems
A cache keyed by a record with an array component never hits, and grows without bound because every lookup inserts a new key.
An idempotency check that compares incoming requests as records treats every retry as new, so a retried return request is processed twice.
Test assertions with assertEquals on two such records fail even when the data matches, and developers sometimes "fix" the test by comparing toString output, which compares identity hashes and fails randomly.
A record exposed from a service object through its accessor lets any caller edit the service's internal state.
Verification
The companion code has eleven plain-Java checks covering every behaviour above: reference equality, equality only for a shared array instance, the failing HashSet lookup, the identity toString, mutation through the caller's array and through the accessor, the defensive copies in both directions, content-based equals, hashCode and toString for the safe record, and the unmodifiable List component. Compile with javac and run java RecordArraysTest; it prints 11 checks passed on Java 23.0.2 and needs no dependencies.
Run the example yourself
The three record versions, the demonstration run and eleven plain-Java checks. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.