equals vs Arrays.equals in Java

前端 未结 8 1396
走了就别回头了
走了就别回头了 2020-11-21 23:29

When comparing arrays in Java, are there any differences between the following 2 statements?

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


        
相关标签:
8条回答
  • 2020-11-22 00:10

    The Arrays.equals(array1, array2) :

    check if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.

    The array1.equals(array2) :

    compare the object to another object and return true only if the reference of the two object are equal as in the Object.equals()

    0 讨论(0)
  • 2020-11-22 00:10
    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));
    
       }
    }
    

    Here is the output:

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

    Seeing this kind of problem I would personally go for Arrays.equals(array1, array2) as per your question to avoid confusion.

    0 讨论(0)
提交回复
热议问题