Java中的等于vs Arrays.equals

Pan*_*nda 202 java arrays equality

在比较Java中的数组时,以下两个语句之间是否有任何区别?

array1.equals(array2);
Arrays.equals(array1, array2);
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*rey 286

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

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


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

  • 请注意,`Arrays.equals()`对于多维数组不起作用,它只比较第一维的项以获得引用相等性.Apache commons`ArrayUtils.isEquals`适用于多维数组. (57认同)
  • @AdamParkin为什么我们有[`Arrays.deepEquals(Object [],Object [])`](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepEquals %28java.lang.Object [],%20java.lang.Object []%29). (45认同)
  • 我惊呆了.是否有理由将array.equals实现为指针比较而不是比较长度和每个对象? (4认同)
  • @JeewanthaSamaraweera这是该法的定义,但是对于`.equals`它不比较的内容这就是为什么你需要的方法. (3认同)
  • @Lake确实比较了数组长度和包含的对象,但它没有做的是深度比较.事实上equals确实可以正常工作,因为数组已经被打破了,这首先应该不是问题. (2认同)

alf*_*alf 82

这是一个臭名昭着的问题:.equals()对于阵列严重破坏,只是不要使用它.

也就是说,它并没有像"有人以一种非常错误的方式做到"那样"破碎" - 它只是做了定义的而不是通常所期望的.因此对于纯粹主义者来说:它完全没问题,这也意味着,永远不要使用它.

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

所以,不同的是,Arrays.equals(array1, array2)工作正如你所期望(即比较内容),array1.equals(array2)回落到Object.equals实现,这反过来又比较认同,从而更好地替换==(对于较真:是的,我知道null).

问题是,Arrays.equals(array1, array2)如果数组的元素没有equals正确实现,甚至会咬你.我知道,这是一个非常幼稚的陈述,但有一个非常重要的不太明显的案例:考虑一个二维数组.

Java中的2D数组是一个数组数组,并且数组' equals被破坏(或者如果您愿意,则无​​用),因此Arrays.equals(array1, array2)在2D数组上无法正常工作.

希望有所帮助.

  • 它没有被破坏,它只是继承自Object. (12认同)
  • 对于数组数组,需要[`Arrays.deepEquals`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#deepEquals-java.lang.Object:A -java.lang.Object:A-)---这是`someArray.equals`一直应该做的事情.(相关:[`Objects.deepEquals`](https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#deepEquals-java.lang.Object-java.lang.Object - )). (2认同)

Eng*_*uad 16

查看两种方法的实现,深入理解它们:

array1.equals(array2);
Run Code Online (Sandbox Code Playgroud)
/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

而:

Arrays.equals(array1, array2);
Run Code Online (Sandbox Code Playgroud)
/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)


小智 11

叹.早在70年代,我就是IBM 370系统的"系统程序员"(sysadmin),我的雇主是IBM用户组SHARE的成员.有时候有人会就某些CMS命令的某些意外行为提交APAR(错误报告),IBM会回复NOTABUG:该命令执行它的设计目的(以及文档中所说的内容).

SHARE提出了一个与此相反的方法:坏 - 按设计破碎.我认为这可能适用于数组的equals实现.

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

但该逻辑不适用于数组.数组有数据,你希望比较(通过equals)来比较数据.理想情况下,Arrays.deepEquals的方式,但至少Arrays.equals的方式(元素的浅层比较).

所以问题是数组(作为内置对象)不会覆盖Object.equals.String(作为命名类)覆盖Object.equals并提供您期望的结果.

给出的其他答案是正确的:[...].equals([....])只是比较指针而不是内容.也许有一天有人会纠正这个.或者可能不是:如果[...]等于实际比较元素,那么有多少现有程序会破坏?我怀疑并不多,但不仅仅是零.

  • 我喜欢Broken.As.Designed的缩写 (4认同)

Ada*_*man 5

数组继承equals()Object,因此比较仅比较反对它的数组返回true.

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

这个片段阐明了不同之处:

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
Run Code Online (Sandbox Code Playgroud)

另见Arrays.equals().另一种静态方法也可能是有意义的:Arrays.deepEquals().