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

ⅰ亾dé卋堺 提交于 2020-01-01 09:04:53

问题


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)


回答1:


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).




回答2:


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

  • Java Arrays.equals() returns false for two dimensional arrays


来源:https://stackoverflow.com/questions/2555753/best-way-to-compare-between-two-dimension-integer-arrays-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!