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

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

问题描述

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

I have two object arrays like so:

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

我想知道,如果数组是相等的。我限定等于如数组1的每个值是相同的,在该数组2该位置的值。因此,这两个数组是相等的。

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?

编辑:我需要一个等于可以进入嵌套阵列

I needed an equals that can go into nested arrays.

推荐答案

使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html\"><$c$c>Arrays.deepEquals().这做相同的工作为满足Arrays.equals(),但也与嵌套数组。

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

如果两个指定数组彼此是深层彼此相等,则返回true。不同于等于(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.

两个数组引用被认为是深层相等的,如果都为null,或者它们引用了包含相同元素数量的数组,并在两个数组元素的所有相应对深感平等的。

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。

  •   

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

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天全站免登陆