← 中文资源

简体中文版本

Objects.deepEquals 递归比较嵌套数组与空值

对比 Objects.equals 与 Objects.deepEquals:后者在未知运行时类型时也能递归比较基本类型数组与嵌套 Object[],并安全处理 null 引用。

阅读英文原文

实现说明

Objects.deepEquals 递归比较嵌套数组与空值的核心是类 GenericArrayEquality和函数 main。

使用要点

  • 语言原生工具链独自即足够跑通——运行过程不会触发外部依赖解析。
  • 直接运行文件,输出会带上标签,比如 Objects.equals(int[]):、Objects.deepEquals(int[]):、shallow equals(Object[]):——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Objects.deepEquals 递归比较嵌套数组与空值」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 Objects.equals(int[]):、Objects.deepEquals(int[]):、shallow equals(Object[]): 这类标签。

签名一览:public static void main(String[] args)

核心语句

Object[] treeA = { "cfg", new int[] { 1, 2 }, new String[] { "a", "b" } };
Object[] treeB = { "cfg", new int[] { 1, 2 }, new String[] { "a", "b" } };
Object right = new int[] { 10, 20, 30 };

代码示例

import java.util.Objects;

public class GenericArrayEquality {

    public static void main(String[] args) {
        Object left = new int[] { 10, 20, 30 };
        Object right = new int[] { 10, 20, 30 };

        // Objects.equals delegates to array.equals(), which checks reference identity only
        System.out.println("Objects.equals(int[]):     " + Objects.equals(left, right));
        // Objects.deepEquals inspects primitive and nested Object[] arrays recursively
        System.out.println("Objects.deepEquals(int[]): " + Objects.deepEquals(left, right));

        Object[] treeA = { "cfg", new int[] { 1, 2 }, new String[] { "a", "b" } };
        Object[] treeB = { "cfg", new int[] { 1, 2 }, new String[] { "a", "b" } };
        System.out.println("shallow equals(Object[]):  " + Objects.equals(treeA, treeB));
        System.out.println("deepEquals(Object[]):      " + Objects.deepEquals(treeA, treeB));

        // Null inputs never throw NullPointerException
        System.out.println("null == null: " + Objects.deepEquals(null, null)
                + ", array == null: " + Objects.deepEquals(left, null));
    }
}