如何比较 Java 中的两个对象数组? [英] How to compare two object arrays in Java?

查看:47
本文介绍了如何比较 Java 中的两个对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two object arrays like so:

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

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

I would like to know if the arrays are equal. I'm defining equal as every value in array1 is the same as the value in that position in the array2. So these two arrays would be equal.

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

What is the best why to find out if these two arrays are equal?

if(array1 == array2) 

不是一个深等于,所以它不起作用,我不知道循环每个元素并比较它们是否是解决这个问题的最好和最有效的方法.大家有什么更好的建议吗?

is not a deep equals so that won't work and I don't know if looping over each element and comparing them is the best and most efficient way to solve this problem. Does anyone have any better suggestions?

我需要一个可以进入嵌套数组的equals.

I needed an equals that can go into nested arrays.

推荐答案

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

Use Arrays.deepEquals(). This does the same job as Arrays.equals() but also works with nested arrays.

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

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.

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

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

  • e1 和 e2 都是对象引用类型的数组,Arrays.deepEquals(e1, e2) 将返回 true
  • e1 和 e2 是相同基本类型的数组,适当重载 Arrays.equals(e1, e2) 将返回 true.
  • e1 == e2
  • e1.equals(e2) 将返回 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 中的两个对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆