Comparing Arrays in Java: equals vs Arrays.equals
When comparing array objects in Java, it's important to understand the subtle differences between equals and Arrays.equals.
equals Operator
The equals operator in Java compares whether two references refer to the same object in memory. When applied to arrays, this means it checks if the two array references are pointing to the same array instance.
Object[] array1, array2; array1.equals(array2);
In this case, if array1 and array2 refer to the same array object, the result will be true. Otherwise, it will be false.
Arrays.equals Method
In contrast, the Arrays.equals method compares the contents of two arrays. It checks if the arrays have the same number of elements and if the corresponding elements are equal.
Arrays.equals(array1, array2);
If array1 and array2 have the same contents, the result will be true. Otherwise, it will be false.
Key Differences
The key difference between equals and Arrays.equals is that equals compares references while Arrays.equals compares contents.
Examples
Consider the following examples:
Object[] array1 = new int[] { 1, 2, 3 }; Object[] array2 = new int[] { 1, 2, 3 };
In this case, array1.equals(array2) will be false because array1 and array2 are two different array objects. However, Arrays.equals(array1, array2) will be true because the contents of the arrays are the same.
Object[] array1 = new int[] { 1, 2, 3 }; Object[] array2 = array1;
In this case, array1.equals(array2) and Arrays.equals(array1, array2) will both be true because array1 and array2 refer to the same array object.
The above is the detailed content of Java Array Comparison: `equals()` vs. `Arrays.equals()` - What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!