在Java中等于equals vs Arrays.equals

equals vs Arrays.equals in Java

比较Java中的数组时,以下2条语句之间是否有区别?

1
2
array1.equals(array2);
Arrays.equals(array1, array2);

如果是这样,它们是什么?


array1.equals(array2)array1 == array2相同,即它是同一数组。正如@alf指出的那样,这不是大多数人期望的。

Arrays.equals(array1, array2)比较数组的内容。

同样,array.toString()可能不是很有用,您需要使用Arrays.toString(array)


这是一个臭名昭著的问题:数组的.equals()严重损坏,只是永远不要使用它。

就是说,它不是像"某人以错误的方式完成的"那样"破碎"的,它只是在执行已定义的内容,而不是通常所期望的。因此,对于纯粹主义者:这是非常好的,这也意味着永远不要使用它。

现在,equals的预期行为是比较数据。默认行为是比较身份,因为Object没有任何数据(对于纯粹主义者:是的,但不是重点)。假设是,如果子类中需要equals,则将其实现。在数组中,没有适合您的实现,因此您不应该使用它。

所以区别是,Arrays.equals(array1, array2)可以按您期望的方式工作(即比较内容),array1.equals(array2)退回到Object.equals实现,后者反过来比较身份,因此最好用==代替(对于纯粹主义者:是的,我了解null)。

问题是,如果数组元素不能正确实现equals,那么即使Arrays.equals(array1, array2)也会咬你一口。我知道这是一个非常幼稚的声明,但是有一个非常重要的但不太明显的情况:考虑一个2D数组。

Java中的2D数组是数组的数组,并且数组的equals是损坏的(或者,如果您愿意,则是无用的),因此Arrays.equals(array1, array2)不能像您期望的那样在2D数组上工作。

希望能有所帮助。


查看这两种方法的实现以深入了解它们:

1
array1.equals(array2);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
 * 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 reflexive: for any non-null reference value
 *     {@code x}, {@code x.equals(x)} should return
 *     {@code true}.
 *
<li>
It is symmetric: 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 transitive: 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 consistent: 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);
}

而:

1
Arrays.equals(array1, array2);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Returns <tt>true</tt> if the two specified arrays of Objects are
 * equal 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 equal 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提出了一个反驳:BAD-按设计破碎。我认为这可能适用于equals for arrays的实现。

Object.equals的实现没有错。对象没有数据成员,因此没有可比较的对象。当且仅当两个"对象"实际上是相同的对象(内部具有相同的地址和长度)时,它们才相等。

但是,这种逻辑不适用于数组。数组具有数据,并且您希望比较(通过等于)比较数据。理想情况下,使用Arrays.deepEquals的方式,但是至少使用Arrays.equals的方式(元素的浅比较)。

因此,问题在于数组(作为内置对象)不会覆盖Object.equals。字符串(作为命名类)确实会覆盖Object.equals并给出您期望的结果。

给出的其他答案是正确的:[...]。equals([....])仅比较指针而不是内容。也许有一天有人会纠正这个问题。也许不是:如果相等地比较元素,多少个现有程序会中断?我怀疑不是很多,但超过零。


数组从Object继承equals(),因此,如果仅将数组与自身进行比较,则compare仅返回true。

另一方面,Arrays.equals比较数组的元素。

该代码段阐明了差异:

1
2
3
4
5
6
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)

将对象与另一个对象进行比较,仅当两个对象的引用与Object.equals()中的相等时才返回true


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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));

   }
}

这是输出:

1
2
3
4
5
    array1 and array2 equal: false
    array1 and array2 equal: false

    array1 and array3 equal: true
    array1 and array3 equal: false

看到这种问题,我将根据您的问题亲自寻求Arrays.equals(array1, array2)以避免混淆。


数组的equals()是从Object继承的,因此它不会查看错误的内容,它仅将每个数组视为与自己相等。

Arrays.equals()方法确实比较数组的内容。所有原始类型都有重载,而对象的重载则使用对象自己的equals()方法。