java中比较二维整数数组的最佳方法

发布于 2024-08-26 22:41:32 字数 61 浏览 4 评论 0原文

我想知道比较二维整数数组的最佳、最快和最简单的方法是什么。 数组的长度是相同的。 (其中一个数组是临时数组)

I would like to know what is the best, fastest and easiest way to compare between 2-dimension arrays of integer.
the length of arrays is the same. (one of the array's is temporary array)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红墙和绿瓦 2024-09-02 22:41:32

伊丹写道:

只需看看值是否相同

如果您想检查所有元素的 a[i][j] 是否等于 b[i][j],只需使用Arrays.deepEquals(a, b)。

Edan wrote:

just need to see if the value is the same

If you want to check that a[i][j] equals b[i][j] for all elements, just use Arrays.deepEquals(a, b).

堇色安年 2024-09-02 22:41:32

看看 java.util.Arrays;它有许多您应该熟悉的数组实用程序。

import java.util.Arrays;

int[][] arr1;
int[][] arr2;
//...
if (Arrays.deepEquals(arr1, arr2)) //...

来自 API

如果两个指定的数组彼此深度相等,则返回true。与 equals(Object[],Object[]) 方法不同,此方法适合与任意深度的嵌套数组一起使用。

请注意,在 Java 中,int[][]Object[] 的子类型。 Java 并没有真正的二维数组。它有数组的数组。

此处显示了嵌套数组的 equalsdeepEquals 之间的区别(请注意,默认情况下 Java 使用零作为元素初始化 int 数组)。

    import java.util.Arrays;
    //...

    System.out.println((new int[1]).equals(new int[1]));
    // prints "false"

    System.out.println(Arrays.equals(
        new int[1],
        new int[1]
    )); // prints "true"
    // invoked equals(int[], int[]) overload

    System.out.println(Arrays.equals(
        new int[1][1],
        new int[1][1]
    )); // prints "false"
    // invoked equals(Object[], Object[]) overload

    System.out.println(Arrays.deepEquals(
        new int[1][1],
        new int[1][1]
    )); // prints "true"

相关问题

Look at java.util.Arrays; it has many array utilities that you should familiarize yourself with.

import java.util.Arrays;

int[][] arr1;
int[][] arr2;
//...
if (Arrays.deepEquals(arr1, arr2)) //...

From the API:

Returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object[],Object[]) method, this method is appropriate for use with nested arrays of arbitrary depth.

Note that in Java, int[][] is a subtype of Object[]. Java doesn't really have true two dimensional arrays. It has array of arrays.

The difference between equals and deepEquals for nested arrays is shown here (note that by default Java initializes int arrays with zeroes as elements).

    import java.util.Arrays;
    //...

    System.out.println((new int[1]).equals(new int[1]));
    // prints "false"

    System.out.println(Arrays.equals(
        new int[1],
        new int[1]
    )); // prints "true"
    // invoked equals(int[], int[]) overload

    System.out.println(Arrays.equals(
        new int[1][1],
        new int[1][1]
    )); // prints "false"
    // invoked equals(Object[], Object[]) overload

    System.out.println(Arrays.deepEquals(
        new int[1][1],
        new int[1][1]
    )); // prints "true"

Related questions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文