1.问题的产生:基本数据类型数组无法使用Comparator函数式接口,进行倒序排序

        int[] nums=new int[]{2,12,341,11,1};
        Arrays.sort(nums,(a,b)->b-a); //该语句会报错

原因:sort(T[] a, Comparator<? super T> c)

   int[]不是T[](Integer[]将是),无法使用Comparator函数式接口。

2.解决方法:

  (1)先升序后反转数组

Arrays.sort(nums);
for(int i=0;i<nums.length/2;i++){
    int temp=nums[i];
    nums[i]=nums[nums.length-1-i];
    nums[nums.length-1-i]=temp;    
}

  (2)将nums转换为Integer数组,再调用该方法

        Integer[] newNums=Arrays.stream(nums).boxed().toArray(Integer[]::new);
        Arrays.sort(newNums,(a,b)->b-a);

相关文章:

  • 2021-11-20
  • 2022-12-23
  • 2021-06-22
  • 2021-07-19
  • 2021-10-31
  • 2021-07-19
  • 2021-05-25
猜你喜欢
  • 2021-11-18
  • 2021-04-15
  • 2022-01-21
  • 2022-01-20
  • 2022-12-23
  • 2021-04-30
  • 2021-09-29
相关资源
相似解决方案