简体   繁体   English

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

[英]How to compare two 2D Arrays in Java?

I am a beginner trying to write a function in Java that returns true if two passed 2D arrays of int type are the same size in every dimension, and false otherwise. 我是一个尝试在Java中编写函数的初学者,如果两个传递的int类型的二维数组在每个维度中的大小相同,则返回true否则返回false Requirements are that if both arrays are null you should return true . 要求是如果两个数组都为null ,则应返回true If one is null and the other is not you should return false . 如果一个为null而另一个不为,则应返回false

Somehow getting an error for my code: 以某种方式为我的代码收到错误:

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

Any help would be appreciated! 任何帮助,将不胜感激!

Edit: Problem is "Runtime Error: null" 编辑:问题是“运行时错误:null”

Your logic looks almost spot-on already. 你的逻辑看起来几乎已经发现了。 The only issue I see is in the logic handling the case where both arrays are not null and have the same first dimension. 我看到的唯一问题是逻辑处理两个数组都不为空具有相同的第一维的情况。 You should be returning false if any index does not have matching lengths: 如果任何索引没有匹配的长度,您应该返回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;
}

Follow the demo link below to see some of examples of this method working correctly. 按照下面的演示链接查看此方法的一些示例正常工作。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM