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