Gra*_*min 12 java arrays equals object
我有两个对象数组,如下所示:
Object[] array1 = {0, 1, 2, 3};
Object[] array2 = {0, 1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
我想知道数组是否相等.我定义相等,因为array1中的每个值都与array2中该位置的值相同.所以这两个数组是相同的.
找出这两个数组是否相等的最佳原因是什么?
if(array1 == array2)
Run Code Online (Sandbox Code Playgroud)
不是一个深度等于所以不会工作,我不知道是否循环每个元素并比较它们是解决这个问题的最佳和最有效的方法.有没有人有更好的建议?
编辑:我需要一个可以进入嵌套数组的等号.
Mar*_*elo 21
使用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 <tt>true</tt> if the two specified arrays of Objects are
* <i>equal</i> 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 <tt>e1</tt>
* and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null
* : e1.equals(e2))</tt>. 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 <tt>null</tt>.<p>
*
* @param a one array to be tested for equality.
* @param a2 the other array to be tested for equality.
* @return <tt>true</tt> if the two arrays are equal.
*/
public static boolean equals(Object[] a, Object[] a2)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
45716 次 |
最近记录: |