← 中文资源

简体中文版本

Record 数组组件的相等性陷阱

record 自动生成的 equals 对数组组件按引用比较:内容相同的两个 int 数组也不相等。换成 List 组件即可获得值相等。

阅读英文原文

实现说明

逻辑集中在类 VoteBatches、component、Score、ScoreFixed和函数 main里。

使用要点

  • 直接运行文件,输出会带上标签,比如 array equals:、array hashCode equal:、toString:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Record 数组组件的相等性陷阱」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 array equals:、array hashCode equal:、toString: 这类标签。

核心语句

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

代码示例

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());
    }
}