Learn how to remove duplicate elements from 2D array in Java using loops and Arrays.equals() method. A 2D or multidimensional array is an array of arrays. In this example, we will identify duplicate rows and print only the unique rows.
Code Explanation (Step-by-Step)
- Here first, we create a 2D array containing duplicate rows.
- The outer for loop iterates through every row of the 2D array.
- We create a duplicate boolean variable and initialize it to false.
- The inner loop compares the current row with all previously processed rows.
- We use Arrays.equals() to compare the contents of two array rows.
- If both rows contain the same elements in the same order, the row is considered a duplicate.
- When a duplicate row is found, duplicate becomes true, and the inner loop stops.
- Only rows that have not appeared previously are printed using Arrays.toString().
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args) {
int[][] arr = {
{3, 4, 5},
{6, 7, 8},
{1, 2},
{3, 4, 5}
};
for (int i = 0; i < arr.length; i++) {
boolean duplicate = false;
for (int j = 0; j < i; j++) {
if (Arrays.equals(arr[i], arr[j])) {
duplicate = true;
break;
}
}
if (!duplicate) {
System.out.println(Arrays.toString(arr[i]));
}
}
}
}
Output :-
[3, 4, 5]
[6, 7, 8]
[1, 2]
Why Should We Not Use == to Compare Java Arrays?
We should not use the == operator to compare the contents of Java arrays because == checks whether two array variables refer to the same object in memory.
In the below example, even though arr1 and arr2 contain the same elements, they are two different array objects. Therefore, arr1 == arr2 returns false.
Example:
int[] arr1 = {3, 4, 5};
int[] arr2 = {3, 4, 5};
System.out.println(arr1 == arr2);
Output :-
false
Use Arrays.equals() Instead
To compare the contents of two arrays, use:
int[] arr1 = {3, 4, 5};
int[] arr2 = {3, 4, 5};
System.out.println(Arrays.equals(arr1, arr2));
Output :-
true