programing

Java에서는 Arrays.equals와 동등합니다.

prostudy 2022. 7. 5. 22:12
반응형

Java에서는 Arrays.equals와 동등합니다.

Java에서 어레이를 비교할 때 다음 두 문장에 차이가 있습니까?

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).

이것은 악명 높은 문제입니다..equals()어레이가 심하게 파손되어 있기 때문에 사용하지 마십시오.

즉, 「누군가가 정말로 잘못된 방법으로 그것을 실행했다」와 같이 「부러졌다」는 것은 아닙니다.통상적으로 기대되고 있는 것이 아니라, 정의된 대로 실행하는 것입니다.순수주의자들에게는, 그것은 완벽하게 괜찮고, 그것은 또한 절대 사용하지 말라는 것을 의미합니다.

이제 예상되는 동작은equals데이터를 비교하는 것입니다.디폴트 동작은 ID를 비교하는 것입니다.Object데이터가 없습니다(순수주의자의 경우: 있습니다만, 요점은 아닙니다).필요한 경우 가정은 다음과 같습니다.equals서브클래스에서는, 실장할 수 있습니다.어레이에서는 구현이 없기 때문에 사용하지 않도록 되어 있습니다.

다른 점은,Arrays.equals(array1, array2)예상대로 동작한다(즉, 컨텐츠의 비교),array1.equals(array2)로 되돌아가다Object.equals돌리고, 그리고 빠르게로 대체 정체성 비교하여 도입,.==순수 주의자(:yes 내가 아는.null).

문제는, 심지어는Arrays.equals(array1, array2)만약 배열의 요소를 실행하지 않고 열심히 당신이 물게.equals적절히.이것은 매우 순진한 성명, 나는 알고 있지만, 매우 중요한less-than-obvious 사건:2D배열을 고려해요.

배열의 자바에 2차원 배열은 배열 및 arrays'.equals부서진(당신이 선호한다면거나 쓸모 없는), 그렇구나.Arrays.equals(array1, array2)당신이 2차원 배열에 대해 기대한다 일하지는 않을 거에요.

도움이 됐으면 좋겠다.

다음 두 가지 방법의 구현에 대해 자세히 알아봅니다.

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이 NOTAB에 응답하는 경우가 있습니다.UG: 이 명령어는 설계한 작업(및 매뉴얼에 기재된 작업)을 수행합니다.

SHARE는 이에 대한 대응책을 내놓았습니다.BAD --Broken As Design.이는 어레이에 대한 동등한 구현에 적용될 수 있다고 생각합니다.

Object.equals 구현에는 문제가 없습니다.개체에 데이터 멤버가 없으므로 비교할 항목이 없습니다.두 개의 "개체"는 실제로 동일한 개체(내부적으로는 동일한 주소 및 길이)인 경우에만 동일합니다.

그러나 이 논리는 어레이에는 적용되지 않습니다.어레이에는 데이터가 있으며 동등하게 비교를 통해 데이터를 비교해야 합니다.이상적인 것은 어레이 방식입니다.deepEquals는 가능하지만 적어도 Arrays.equals와 같은 방식입니다(요소의 비교를 가능하게 합니다).

따라서 어레이(내장 객체)가 Object.equals를 덮어쓰지 않는 것이 문제입니다.문자열(이름 있는 클래스)은 Object.equals를 덮어쓰고 원하는 결과를 제공합니다.

다른 답변은 정답입니다.[...].equals([....])는 단순히 포인터를 비교하고 내용은 비교하지 않습니다.언젠가 누군가 이걸 고쳐줄지도 몰라.그렇지 않을 수도 있습니다. [...]가 실제로 요소를 비교할 경우 기존 프로그램이 몇 개나 중단됩니까?많지는 않지만, 0개 이상일 거예요.

Arrays 어레이 상속을 물려받equals()부터에서Object만약 자체에 대해 배열을 비교하는 그래서만에서 true를 반환하면 비교해 보겠습니다.따라서 compare는 배열을 자체와 비교할경우에만 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

도 참조해 주세요.또 다른 스태틱 방식도 있습니다:

그 그Arrays.equals(array1, array2)

두 배열에 동일한 수의 요소가 포함되어 있는지, 두 배열에 해당하는 모든 요소 쌍이 동일한지 확인합니다.

array1.equals(array2):

하여 두 한다.Object.equals()

equals()는 서 from from of 。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)★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

언급URL : https://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java

반응형