java - 如何比较Java中的两个对象数组?

标签 java arrays object equals

我有两个像这样的对象数组:

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

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

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

if(array1 == array2) 

不是深度相等,所以不会起作用,我不知道遍历每个元素并比较它们是否是解决此问题的最佳和最有效的方法。有没有人有更好的建议?

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

最佳答案

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

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.

Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.

Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:

  • e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
  • e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
  • e1 == e2
  • e1.equals(e2) would return true.

Note that this definition permits null elements at any depth.

If either of the specified arrays contain themselves as elements either directly or indirectly through one or more levels of arrays, the behavior of this method is undefined.

关于java - 如何比较Java中的两个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6652085/

相关文章:

javascript - 检查对象中是否存在像 "item[ ]"这样的键名 - AngularJs

java - 通过拖动在 libGDX 中真实地旋转 3D 模型

C++ 在临时类中创建数组

javascript - `apply` 没有 't work for function as object' 的属性

java - 如何在 Java 中将锯齿状数组解析为单个变量?

javascript - 按顺序将数组值附加到多个 div

c++ - 如何在另一个类的方法中使用一个类的实例?

java - 在使用 Hibernate 时可以截断数据库表吗?

java - 使用属性访问器方法时的 EclipseLink 实体映射问题

java - 为什么 Android Studio 在选择图像后更改图像旋转