To check if two arrays have the same elements regardless of order in Java, you can sort both arrays and then compare them using the Arrays.equals()
method.
In this example,
arr1
and arr2
with the same elements but in different order.Arrays.sort()
method.Arrays.equals()
method and store the result in the variable equal1
.equal1
to the console.// Java example to check equality of arrays regardless of order
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {3, 1, 2};
Arrays.sort(arr1);
Arrays.sort(arr2);
boolean equal1 = Arrays.equals(arr1, arr2);
System.out.println("Arrays are equal regardless of order: " + equal1);
}
}
Arrays are equal regardless of order: true
In this example,
arr3
and arr4
with different elements.Arrays.sort()
method.Arrays.equals()
method and store the result in the variable equal2
.equal2
to the console.// Java example to check equality of arrays regardless of order
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr3 = {1, 2, 3};
int[] arr4 = {4, 5, 6};
Arrays.sort(arr3);
Arrays.sort(arr4);
boolean equal2 = Arrays.equals(arr3, arr4);
System.out.println("Arrays are equal regardless of order: " + equal2);
}
}
Arrays are equal regardless of order: false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Java language with well detailed examples.