When comparing arrays in Java, are there any differences between the following 2 statements?
Object[] array1, array2;
array1.equals(array2);
Arrays.equals(ar
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().