当比较Java中的数组时,下面两个语句之间有什么不同吗?

Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);

如果有,它们是什么?


当前回答

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

数组。Equals (array1, array2)比较数组的内容。


类似地,array. tostring()可能不是很有用,你需要使用Arrays.toString(array)。

其他回答

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

另一方面,数组。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

请参见Arrays.equals()。另一个静态方法可能也很有趣:Arrays.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;
}
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

看到这类问题,我个人倾向于使用数组。= (array1, array2)根据你的问题来避免混淆。

的数组。Equals (array1, array2):

检查两个数组是否包含相同数量的元素,并且两个数组中所有对应的元素对都相等。

array1.equals(array2):

将该对象与另一个对象进行比较,只有当两个对象的引用相等时才返回true,就像在object .equals()中那样

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

也就是说,它并不是“坏了”,就像“某人以一种非常错误的方式做了这件事”——它只是做了定义的事情,而不是通常期望的事情。所以对于纯粹主义者来说:它完全没问题,这也意味着,永远不要使用它。

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

区别在于,数组。equals(array1, array2)工作如你所料(即比较内容),array1.equals(array2)回落到Object。equals实现,它反过来比较身份,因此最好用==代替(对于纯粹主义者:是的,我知道null)。

问题是,即使是数组。如果数组的元素没有正确地实现Equals,那么Equals (array1, array2)会让你很难受。我知道这是一个非常天真的说法,但有一个非常重要的不太明显的情况:考虑一个2D数组。

在Java中,2D数组是数组的数组,而数组的等号是坏的(如果你愿意,也可以是无用的),所以数组。equals(array1, array2)在2D数组上不能正常工作。