【发布时间】:2012-02-05 07:53:39
【问题描述】:
在Java中比较数组时,下面2个语句有区别吗?
Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);
如果有,它们是什么?
【问题讨论】:
-
看看 java.util.Arrays.deepEquals(Object[] a1, Object[] a2)
在Java中比较数组时,下面2个语句有区别吗?
Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);
如果有,它们是什么?
【问题讨论】:
array1.equals(array2) 与array1 == array2 相同,即它是同一个数组。正如@alf 指出的那样,这不是大多数人所期望的。
Arrays.equals(array1, array2) 比较数组的内容。
同样array.toString()可能不是很有用,你需要使用Arrays.toString(array)。
【讨论】:
Arrays.equals() 对于多维数组不能按预期工作,它只比较第 1 维的项目的引用相等性。 Apache commons ArrayUtils.isEquals 适用于多维数组。
Arrays.deepEquals(Object[], Object[])。
.equals 它不比较内容,这就是您需要该方法的原因。
这是一个臭名昭著的问题:.equals() 数组严重损坏,永远不要使用它。
也就是说,它并没有像“有人以一种非常错误的方式完成它”那样“被破坏”——它只是在做定义的事情,而不是通常预期的事情。所以对于纯粹主义者来说:这完全没问题,这也意味着,永远不要使用它。
现在equals 的预期行为是比较数据。默认行为是比较身份,因为Object 没有任何数据(对于纯粹主义者:是的,它有,但这不是重点);假设是,如果您在子类中需要equals,您将实现它。在数组中,没有适合你的实现,所以你不应该使用它。
所以区别在于,Arrays.equals(array1, array2) 工作正如您所期望的那样(即比较内容),array1.equals(array2) 回退到 Object.equals 实现,后者又比较身份,因此更好地替换==(纯粹主义者:是的,我知道null)。
问题是,如果数组元素没有正确实现equals,即使Arrays.equals(array1, array2) 也会咬你一口。我知道,这是一个非常幼稚的说法,但有一个非常重要的不太明显的情况:考虑一个二维数组。
Java 中的二维数组是数组的数组,而数组的 equals 已损坏(如果您愿意,也可以无用),因此 Arrays.equals(array1, array2) 在二维数组上将无法正常工作。
希望对您有所帮助。
【讨论】:
equals() 的自定义实现?我认为 is 没有被 Object 覆盖。
Arrays.deepEquals --- 这是someArray.equals 应该一直做的。 (相关:Objects.deepEquals。)
深入了解这两种方法的实现:
array1.equals(array2);
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
同时:
Arrays.equals(array1, array2);
/**
* 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) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++) {
Object o1 = a[i];
Object o2 = a2[i];
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return true;
}
【讨论】:
叹息。早在 70 年代,我是 IBM 370 系统的“系统程序员”(sysadmin),我的雇主是 IBM 用户组 SHARE 的成员。有时有人会针对某些 CMS 命令的某些意外行为提交 APAR(错误报告),而 IBM 会回复 NOTABUG:该命令执行其设计目的(以及文档所述)。
SHARE 对此提出了反驳意见:糟糕——按设计损坏。我认为这可能适用于数组的 equals 实现。
Object.equals 的实现没有错。对象没有数据成员,所以没有什么可比较的。当且仅当它们实际上是相同的 Object(在内部,相同的地址和长度)时,两个“Object”才相等。
但该逻辑不适用于数组。数组有数据,你希望比较(通过等号)来比较数据。理想情况下,Arrays.deepEquals 的方式,但至少 Arrays.equals 的方式(元素的浅比较)。
所以问题是数组(作为内置对象)不会覆盖 Object.equals。字符串(作为命名类)确实覆盖 Object.equals 并给出您期望的结果。
给出的其他答案是正确的: [...].equals([....]) 只是比较指针而不是内容。也许有一天有人会纠正这个。或者可能不是:如果 [...].equals 实际比较元素,有多少现有程序会中断?我怀疑不是很多,但超过零。
【讨论】:
数组从Object 继承equals(),因此仅当将数组与自身进行比较时,compare 才会返回 true。
另一方面,Arrays.equals 比较数组的元素。
这个 sn-p 阐明了区别:
Object o1 = new Object();
Object o2 = new Object();
Object[] a1 = { o1, o2 };
Object[] a2 = { o1, o2 };
System.out.println(a1.equals(a2)); // prints false
System.out.println(Arrays.equals(a1, a2)); // prints true
另见Arrays.equals()。另一个静态方法可能也很有趣:Arrays.deepEquals()。
【讨论】:
Arrays.equals(array1, array2):
检查两个数组是否包含相同数量的元素,并且两个数组中所有对应的元素对是否相等。
array1.equals(array2):
将对象与另一个对象进行比较,仅当两个对象的引用相等时才返回 true,如 Object.equals() 中所示
【讨论】:
数组的equals()继承自Object,所以它不看数组的内容,只认为每个数组都等于自己。
Arrays.equals() 方法做比较数组的内容。所有原始类型都有重载,对象的重载使用对象自己的equals() 方法。
【讨论】:
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing three object arrays
Object[] array1 = new Object[] { 1, 123 };
Object[] array2 = new Object[] { 1, 123, 22, 4 };
Object[] array3 = new Object[] { 1, 123 };
// comparing array1 and array2
boolean retval=Arrays.equals(array1, array2);
System.out.println("array1 and array2 equal: " + retval);
System.out.println("array1 and array2 equal: " + array1.equals(array2));
// comparing array1 and array3
boolean retval2=Arrays.equals(array1, array3);
System.out.println("array1 and array3 equal: " + retval2);
System.out.println("array1 and array3 equal: " + array1.equals(array3));
}
}
这是输出:
array1 and array2 equal: false
array1 and array2 equal: false
array1 and array3 equal: true
array1 and array3 equal: false
看到这种问题,我会根据您的问题亲自前往Arrays.equals(array1, array2) 以避免混淆。
【讨论】: