有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中比较两个2D数组?

我是一个试图用Java编写函数的初学者,如果两个传递的int类型的2D数组在每个维度上的大小相同,则返回true,否则返回false。要求是,如果两个数组都是null,则应返回true。如果一个是null,另一个不是,则应返回false

不知怎的,我的代码出现了一个错误:

public static boolean arraySameSize(int[][] a, int[][] b) {
    if (a == null && b == null) {
        return true;
    }
    if (a == null || b == null) {
        return false;
    }
    if (a.length == b.length) {
        for (int i = 0; i < a.length; i++) {
            if (a[i].length == b[i].length) {
                return true;
            }
        }   
    }
    return false;
}

任何帮助都将不胜感激

编辑:问题是“运行时错误:null”


共 (1) 个答案

  1. # 1 楼答案

    你的逻辑看起来已经很正确了。我看到的唯一问题是在处理两个数组都不是空的情况下的逻辑具有相同的第一维度。如果任何索引没有匹配的长度,则应返回false:

    public static boolean arraySameSize(int[][] a, int[][] b) {
        if (a == null && b == null) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        if (a.length != b.length) {
            return false;
        }
    
        // if the code reaches this point, it means that both arrays are not
        // null AND both have the same length in the first dimension
        for (int i=0; i < a.length; i++) {
            if (a[i] == null && b[i] == null) {
                continue;
            }
            if (a[i] == null || b[i] == null) {
                return false;
            }
            if (a[i].length != b[i].length) {
                return false;
            }
        }
    
        return true;
    }
    

    按照下面的演示链接查看此方法正确运行的一些示例

    Demo