如何在Java中比较两个对象数组?

我有两个对象数组,如下所示:

Object[] array1 = {0, 1, 2, 3}; Object[] array2 = {0, 1, 2, 3}; 

我想知道数组是否相等。 我定义相等,因为array1中的每个值都与array2中该位置的值相同。 所以这两个数组是相同的。

找出这两个数组是否相等的最佳原因是什么?

 if(array1 == array2) 

不是一个深度等于所以不会工作,我不知道是否循环每个元素并比较它们是解决这个问题的最佳和最有效的方法。 有没有人有更好的建议?

编辑:我需要一个可以进入嵌套数组的等号。

使用Arrays.deepEquals() 。 这与Arrays.equals()完成相同的工作,但也适用于嵌套数组。

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

如果两个数组引用都为null,则它们被认为是非常相等的,或者如果它们引用包含相同数量的元素的数组,并且两个数组中的所有对应元素对都非常相等。

如果满足以下任何条件,则两个可能为空的元素e1和e2非常相等:

  • e1和e2都是对象引用类型的数组,而Arrays.deepEquals(e1,e2)将返回true
  • e1和e2是相同基元类型的数组,并且Arrays.equals(e1,e2)的适当重载将返回true。
  • e1 == e2
  • e1.equals(e2)将返回true。

请注意,此定义允许任何深度的null元素。

如果任一指​​定的数组直接或间接通过一个或多个数组级别将自身包含为元素,则此方法的行为是未定义的。

java.util.Arrays.equals

  /** * Returns true if the two specified arrays of Objects are * equal to one another. The two arrays are considered equal if * both arrays contain the same number of elements, and all corresponding * pairs of elements in the two arrays are equal. Two objects e1 * and e2 are considered equal if (e1==null ? e2==null * : e1.equals(e2)). In other words, the two arrays are equal if * they contain the same elements in the same order. Also, two array * references are considered equal if both are null.

* * @param a one array to be tested for equality. * @param a2 the other array to be tested for equality. * @return true if the two arrays are equal. */ public static boolean equals(Object[] a, Object[] a2)

要比较数组,我会使用Arrays.equals方法:

 if (Arrays.equals(array1, array2)) { // array1 and array2 contain the same elements in the same order } 

在您发布的示例中,数组实际上将包含Integer对象。 在这种情况下, Arrays.equals()就足够了。 但是,如果您的数组包含您的某些对象,则必须在类中实现equals() ,以便Arrays.equals()工作

通常,实用程序类java.util.Arrays非常有用。

  • 如果两个数组被认为是相等的,则两个数组包含相同数量的元素,并且两个数组中的所有元素对相等,使用Arrays.equals
  • 如果两个数组引用都被认为是非常相等的,如果它们都为null,或者它们引用包含相同数量元素的数组,并且两个数组中所有相应的元素对完全相等,则使用Arrays.deepEquals 。 此方法适用于任意深度的嵌套数组。

array1.equals(array2)应该为您提供所需的内容。