Comparing arrays in Java can be tricky because the “==” operator only checks if two array variables reference the same memory location, not if their contents are equal. To compare the actual elements within arrays, you need to use methods like Arrays.equals()
or Arrays.deepEquals()
.
Let’s illustrate why using “==” is insufficient for comparing array content:
// Demonstrates that "==" compares references, not content
public class ArrayComparison {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
if (arr1 == arr2) {
System.out.println("Same");
} else {
System.out.println("Not same"); // Output: Not same
}
}
}
In this example, even though arr1
and arr2
hold the same values, the “==” operator returns “Not same” because they refer to different objects in memory.
How to Compare Arrays in Java
Using Arrays.equals()
The Arrays.equals()
method provides a way to compare the contents of two arrays. It returns true
if both arrays have the same length and all corresponding elements are equal according to their equals()
method (for objects) or direct value comparison (for primitives).
// Using Arrays.equals() for comparison
import java.util.Arrays;
public class ArrayComparison {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
if (Arrays.equals(arr1, arr2)) {
System.out.println("Same"); // Output: Same
} else {
System.out.println("Not same");
}
}
}
However, Arrays.equals()
performs a shallow comparison. It won’t correctly compare nested arrays.
Using Arrays.deepEquals()
for Multidimensional and Nested Arrays
For multidimensional or nested arrays where you need to compare the contents of inner arrays as well, Arrays.deepEquals()
is the solution. It recursively compares the elements of nested arrays.
// Demonstrating Arrays.deepEquals() for nested arrays
import java.util.Arrays;
public class DeepArrayComparison {
public static void main(String[] args)
{
// initializing two integer arrays
int inarr1[] = { 1, 2, 3 };
int inarr2[] = { 1, 2, 3 };
Object[] arr1 = {inarr1};
Object[] arr2 = {inarr2};
if (Arrays.deepEquals(arr1, arr2))
System.out.println("Same"); //Output: Same
else
System.out.println("Not same");
}
}
This method handles deep comparisons, ensuring equality across all levels of nested arrays. It even detects cyclic references to prevent infinite loops during comparison.
Conclusion
When comparing arrays in Java, remember that “==” compares object references. To compare array contents, use Arrays.equals()
for single-dimensional arrays and Arrays.deepEquals()
for multidimensional or nested arrays to ensure accurate comparisons. Choosing the right method is crucial for achieving the desired comparison logic in your code.