equals vs Arrays.equals in Java

前端 未结 8 1400
走了就别回头了
走了就别回头了 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-21 23:48

    Arrays inherit equals() from Object and hence compare only returns true if comparing an array against itself.

    On the other hand, Arrays.equals compares the elements of the arrays.

    This snippet elucidates the difference:

    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
    

    See also Arrays.equals(). Another static method there may also be of interest: Arrays.deepEquals().

提交回复
热议问题