java 在java中比较二维整数数组的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2555753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
best way to compare between two-dimension integer arrays in java
提问by firestruq
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)
我想知道在二维整数数组之间进行比较的最佳、最快和最简单的方法是什么。数组的长度是一样的。(数组之一是临时数组)
回答by Will
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).
回答by polygenelubricants
Look at java.util.Arrays; it has many array utilities that you should familiarize yourself with.
看看java.util.Arrays; 它有许多您应该熟悉的数组实用程序。
import java.util.Arrays;
int[][] arr1;
int[][] arr2;
//...
if (Arrays.deepEquals(arr1, arr2)) //...
From the API:
从API:
Returns
trueif the two specified arrays are deeply equalto one another. Unlike theequals(Object[],Object[])method, this method is appropriate for use with nested arrays of arbitrary depth.
true如果两个指定的数组彼此完全相等,则返回。与该equals(Object[],Object[])方法不同,该方法适用于任意深度的嵌套数组。
Note that in Java, int[][]is a subtype of Object[]. Java doesn't really have true two dimensional arrays. It has array of arrays.
请注意,在 Java 中,int[][]是Object[]. Java 并没有真正的二维数组。它有数组数组。
The difference between equalsand deepEqualsfor nested arrays is shown here (note that by default Java initializes intarrays with zeroes as elements).
嵌套数组equals和deepEquals嵌套数组之间的区别如下所示(请注意,默认情况下,Javaint使用零作为元素初始化数组)。
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"

