使用以下代码对数组进行排序时出现错误

问题描述

我能够获得输出

int arr[][]={{1,2},{2,3},{3,4},{1,3}};
Arrays.sort(arr,(a,b)->(b[0]-a[0]));

但这显示错误

int arr[]={1,2,3,4,5,6};
Arrays.sort(arr,b)->(b-a));
Error:     method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable

在这里想念什么?

解决方法

没有Arrays.sort()接受int[]Comparator的变体,这不足为奇,因为您不能定义Comparator<int>(通用类型参数必须为参考类型)。

如果将数组更改为Integer[],它将起作用:

Integer[] arr={1,2,3,4,5,6};
Arrays.sort(arr,(a,b)->(b-a));

您的第一个代码段有效,因为您的第一个(2D)数组的元素类型是int[]int个数组),并且数组是引用类型。因此,它符合public static <T> void sort(T[] a,Comparator<? super T> c)方法的签名。