I wrote below code to compare to arrays that have same elements but in diff order.
Integer arr1[] = {1,4,6,7,2};
Integer arr2[] = {1,2,7,4,6};
Do you care about duplicate counts? For example, would you need to distinguish between { 1, 1, 2 } and { 1, 2, 2 }? If not, just use a HashSet:
public static boolean compareArrays(Integer[] arr1, Integer[] arr2) {
HashSet set1 = new HashSet(Arrays.asList(arr1));
HashSet set2 = new HashSet(Arrays.asList(arr2));
return set1.equals(set2);
}
If you do care about duplicates, then either you could use a Multiset from Guava.
If you want to stick with the sorting version, why not use the built-in sorting algorithms instead of writing your own?
EDIT: You don't even need to create a copy, if you're happy modifying the existing arrays. For example:
public static boolean compareArrays(Integer[] arr1, Integer[] arr2) {
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
You can also have an optimization for the case where the arrays aren't the same length:
public static boolean compareArrays(Integer[] arr1, Integer[] arr2) {
// TODO: Null validation...
if (arr1.length != arr2.length) {
return false;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}