Record Array Component Equality Pitfall

Records generate equals and hashCode that compare array components by reference, so two identical int arrays never match; store a List instead.

JavaData Integrity

Code

snippet
import java.util.Arrays;
import java.util.List;

public class VoteBatches {

    // int[] 组件:record 生成的 equals 对数组走 Object.equals —— 引用相等,
    // 两个内容相同的数组永远不相等(record component 没有数组的值语义)
    record Score(int[] marks) {}

    // 修复:component 换成不可变 List,值相等交给 List.equals
    record ScoreFixed(List<Integer> marks) {}

    public static void main(String[] args) {
        Score a = new Score(new int[] {90, 85});
        Score b = new Score(new int[] {90, 85});
        System.out.println("array equals: " + a.equals(b));
        System.out.println("array hashCode equal: " + (a.hashCode() == b.hashCode()));
        System.out.println("toString: " + a); // 形如 Score[[I@1b6d3586]] 的身份地址
        System.out.println("Arrays.equals sees contents: " + Arrays.equals(a.marks(), b.marks()));

        ScoreFixed x = new ScoreFixed(List.of(90, 85));
        ScoreFixed y = new ScoreFixed(List.of(90, 85));
        System.out.println("list equals: " + x.equals(y));
        System.out.println("list hashCode equal: " + (x.hashCode() == y.hashCode()));
        System.out.println("list content: " + x.marks());
    }
}

The mechanics

Record Array Component Equality Pitfall is built around the classes VoteBatches, component, Score and ScoreFixed and the function main.

Watch out for

  • The project gains nothing new before this runs.

Using it

The entry-point signature is public static void main(String[] args)

Output lines are prefixed (array equals:, array hashCode equal:, toString:), so the outcome of every step stays visible.

Key statements

ScoreFixed x = new ScoreFixed(List.of(90, 85));
ScoreFixed y = new ScoreFixed(List.of(90, 85));
Score a = new Score(new int[] {90, 85});

Interactive Tools for This Topic

FAQ

What does Record Array Component Equality Pitfall print when run?
The script runs standalone; its 7 labeled outputs include `array equals:`, `array hashCode equal:`, `toString:`.