Comparing arrays that have same elements in different order

前端 未结 6 962
遥遥无期
遥遥无期 2020-12-17 21:26

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};
6条回答
  •  没有蜡笔的小新
    2020-12-17 21:47

    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);
    }
    

提交回复
热议问题