Best way to compare two-dimensional integer arrays in java

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

+7
java arrays compare
source share
2 answers

Edan wrote:

just need to see if the value is the same

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

+11
source share

Take a 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 each other. Unlike the equals(Object[],Object[]) method, this method is suitable for use with nested arrays of arbitrary depth.

Note that in Java, int[][] is a subtype of Object[] . Java does not have real two-dimensional arrays. It has an array of arrays.

Here is the difference between equals and deepEquals for nested arrays (note that by default Java initializes int arrays with zeros 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
+4
source share

All Articles