Comparing arrays that have same elements in different order

前端 未结 6 947
遥遥无期
遥遥无期 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:52

    If you have no duplicates you can turn the arrays into sets:

    new HashSet(Arrays.asList(arr1))
        .equals(new HashSet(Arrays.asList(arr2)))
    

    Otherwise:

    List l1 = new ArrayList(Arrays.asList(arr1));
    List l2 = new ArrayList(Arrays.asList(arr1));
    
    Collections.sort(l1);
    Collections.sort(l2);
    
    l1.equals(l2);
    

提交回复
热议问题