关于 Arrays.sort 的问题,其中 lambda 函数的参数类型省略了



我试图理解其他用户提交的代码,作为对leetcode二进制搜索问题的回答,该问题名为"kWeakestRows";。

假设我有一个称为"1"的2D整数数组;a";。

[[1,0],[3,1],[0,2],[1,3],[4,4]]

如果我想对数组"进行排序;a";乘以每行的第一个值。

因此,按a[0][0]、a[1][0]、a[2][0]、a[3][0]、a[4][0]排序。

Arrays.sort(a, (b, c) -> b[0] - c[0]);

调用排序方法后,我会得到一个数组,看起来像这个

[[0,2],[1,0],[1,3],[3,1],[4,4]]

然后我不确定lambda参数类型(b,c(是如何被省略的?编译器从哪里推断类型?

请注意,b和c的参数类型int[]是如何被省略的。

Arrays.sort(a, (int[] b, int[] c) -> b[0] - c[0]);
Arrays.sort(a, (b, c) -> b[0] - c[0]);

作为参考,这里是我试图理解的代码示例。

public int[] kWeakestRows(int[][] mat, int k) {
//2D matrix to hold the number of solders in a row and the index the row is at
int[][] weakest = new int[mat.length][];
int i = 0;
for (int[] row : mat) {
/*
search method returns the index of the first civilian, so if there
are only 2 solders, the first index of a civilian is 2
*/
int solders = binarySearch(row);    //if there are no civilians, the number of soldiers is the length of the row
weakest[i] = new int[]{solders, i};
i++;
}
//sort weakest by the first value of soldiers
Arrays.sort(weakest, (a, b) -> a[0] - b[0]);
//add the first k indexes to the result array
int[] res = new int[k];
for (int j = 0; j < k; j++) {
res[j] = weakest[j][1];
}
return res;
}

谢谢你抽出时间。

您正在调用的方法的声明如下:

public static <T> void sort(T[] a, Comparator<? super T> c)

这声明了一个引入类型参数T的泛型方法。此参数使您能够将该方法与任何引用类型一起使用。这就像使用一个列表,例如Strings:List<String>,其中StringList中类型参数E的自变量。

T的类型可以在编译时推断(类型推断(,因为数组元素的类型在调用该方法时是已知的。当您调用类似Arrays.sort(weakest, (a, b) -> a[0] - b[0])的方法,并且weakest被声明为int[][]时,很明显元素的类型是int[]

类型是隐式推断的,但您可以像Arrays.<int[]>sort(weakest, (a, b) -> a[0] - b[0])一样显式提供它,这是多余的。lambda表达式的参数类型也是隐式推断的。有关更多详细信息,请参阅目标键入。

我的理解如下-

假设第二个参数基本上是比较器(函数接口(的短期实现,并且比较器的类型参数预计是第一个参数的超类型,那么比较器参数的类型将从第一个参数推断出来,并且假设Integer是其自身的超型,如这里所解释的,这将是编译器不会有任何问题的情况。

方法签名看起来像这样-

public static <T> void sort(T[] a, Comparator<? super T> c)

最新更新