Comparing two arrays in Java involves checking if they are equal in terms of size, order, and elements. You can use manual loops for element-by-element comparison, or depend on built-in methods like Arrays.equals()
or Arrays.deepEquals()
for multidimensional arrays.
To determine if two arrays are equal, the following conditions must be checked:
- Length Equality: Both arrays must have the same length. If their lengths differ, they cannot be equal.
- Element Equality: Each corresponding element in both arrays must be equal in value and order. The comparison is performed index by index.
For multidimensional arrays, nested elements must also satisfy these conditions.
In this post, you will see three program examples to compare arrays in Java: using loops, Arrays.equals(), and Arrays.deepEquals().
1. Compare Two Arrays Using Loops
This program example manually compares two arrays by checking their lengths and elements one by one, providing full control over the comparison logic.
package com.javacodepoint.array;
public class CompareArrays {
public static void main(String[] args) {
int[] arr1 = { 10, 20, 30, 40 };
int[] arr2 = { 10, 20, 30, 40 };
boolean areEqual = true;
if (arr1.length != arr2.length) {
areEqual = false;
} else {
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
areEqual = false;
break;
}
}
}
if (areEqual) {
System.out.println("Arrays are equal.");
} else {
System.out.println("Arrays are not equal.");
}
}
}
OUTPUT:
Arrays are equal.
2. Using Arrays.equals()
This program example leverages the built-in Arrays.equals()
method to efficiently compare single-dimensional arrays, making the code concise and easier to implement.
package com.javacodepoint.array;
import java.util.Arrays;
public class CompareArrays2 {
public static void main(String[] args) {
int[] arr1 = { 10, 20, 30, 40 };
int[] arr2 = { 10, 20, 30, 40 };
if (Arrays.equals(arr1, arr2)) {
System.out.println("Arrays are equal.");
} else {
System.out.println("Arrays are not equal.");
}
}
}
OUTPUT:
Arrays are equal.
3. Compare Multidimensional Arrays Using Arrays.deepEquals()
This program example uses Arrays.deepEquals()
to compare multidimensional arrays, ensuring that nested arrays are checked for equality in structure and content.
package com.javacodepoint.array;
import java.util.Arrays;
public class CompareArrays3 {
public static void main(String[] args) {
int[][] arr1 = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] arr2 = { { 1, 2, 3 }, { 4, 5, 6 } };
if (Arrays.deepEquals(arr1, arr2)) {
System.out.println("Multidimensional arrays are equal.");
} else {
System.out.println("Multidimensional arrays are not equal.");
}
}
}
OUTPUT:
Multidimensional arrays are equal.
Notes:
- Using Loops: Provides full control and is useful for understanding comparison logic but can be verbose.
- Using
Arrays.equals()
orArrays.deepEquals()
: Simplifies comparison and is more efficient for single and multidimensional arrays.
Read Also: Merge Two Arrays. | Reverse an Array in Java.