Java 14 records and arrays
Java arrays pose several challenges for records, and these added a number of constraints to the design. Arrays are mutable, and their equality semantics (inherited from Object) is by identity, not contents.
The basic problem with your example is that you wish that equals()
on arrays meant content equality, not reference equality. The (default) semantics for equals()
for records is based on equality of the components; in your example, the two Foo
records containing distinct arrays are different, and the record is behaving correctly. The problem is you just wish the equality comparison were different.
That said, you can declare a record with the semantics you want, it just takes more work, and you may feel like is is too much work. Here's a record that does what you want:
record Foo(String[] ss) {
Foo { ss = ss.clone(); }
String[] ss() { return ss.clone(); }
public boolean equals(Object o) {
return o instanceof Foo f && Arrays.equals(f.ss, ss);
}
public int hashCode() { return Objects.hash(Arrays.hashCode(ss)); }
}
What this does is a defensive copy on the way in (in the constructor) and on the way out (in the accessor), as well as adjusting the equality semantics to use the contents of the array. This supports the invariant, required in the superclass java.lang.Record
, that "taking apart a record into its components, and reconstructing the components into a new record, yields an equal record."
You might well say "but that's too much work, I wanted to use records so I didn't have to type all that stuff." But, records are not primarily a syntactic tool (though they are syntactically more pleasant), they are a semantic tool: records are nominal tuples. Most of the time, the compact syntax also yields the desired semantics, but if you want different semantics, you have to do some extra work.
List< Integer >
workaround
Workaround: Use a List
of Integer
objects (List< Integer >
) rather than array of primitives (int[]
).
In this example, I instantiate an unmodifiable list of unspecified class by using the List.of
feature added to Java 9. You could just as well use ArrayList
, for a modifiable list backed by an array.
package work.basil.example;
import java.util.List;
public class RecordsDemo
{
public static void main ( String[] args )
{
RecordsDemo app = new RecordsDemo();
app.doIt();
}
private void doIt ( )
{
record Foo(List < Integer >integers)
{
}
List< Integer > integers = List.of( 1 , 2 );
var foo = new Foo( integers );
System.out.println( foo ); // Foo[integers=[1, 2]]
System.out.println( new Foo( List.of( 1 , 2 ) ).equals( new Foo( List.of( 1 , 2 ) ) ) ); // true
System.out.println( new Foo( integers ).equals( new Foo( integers ) ) ); // true
System.out.println( foo.equals( foo ) ); // true
}
}