简体   繁体   English

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

[英]best way to compare between two-dimension integer arrays in java

I would like to know what is the best, fastest and easiest way to compare between 2-dimension arrays of integer. 我想知道在2维整数数组之间进行比较的最佳,最快和最简单的方法是什么。 the length of arrays is the same. 数组的长度是一样的。 (one of the array's is temporary array) (其中一个数组是临时数组)

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) . 如果你想检查所有元素a[i][j]等于b[i][j] ,只需使用Arrays.deepEquals(a, b)

Look at java.util.Arrays ; 看看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 : 来自API

Returns true if the two specified arrays are deeply equal to one another. 如果两个指定的数组彼此非常相等 ,则返回true Unlike the equals(Object[],Object[]) method, this method is appropriate for use with nested arrays of arbitrary depth. equals(Object[],Object[])方法不同,此方法适用于任意深度的嵌套数组。

Note that in Java, int[][] is a subtype of Object[] . 请注意,在Java中, int[][]Object[]的子类型。 Java doesn't really have true two dimensional arrays. Java并不真正具有真正的二维数组。 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). 这里显示了嵌套数组的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"

Related questions 相关问题

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

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