为什么我必须创建一个新的整数数组 B
使用Arrays.sort
和 lambda 函数?
class Solution {
public int[] sortArrayByParity(int[] A) {
Integer[] B = new Integer[A.length];
for (int t = 0; t < A.length; ++t)
B[t] = A[t];
Arrays.sort(B, (a, b) -> Integer.compare(a%2, b%2));
for (int t = 0; t < A.length; ++t)
A[t] = B[t];
return A;
}
}
尝试直接对原始数组进行排序 - Arrays.sort(A, (a, b) -> Integer.compare(a%2, b%2))
- 给出以下编译错误:
The method sort(int[]) in the type Arrays is not applicable for the arguments (int[], ( a, b) -> {})
最佳答案
Arrays.sort
的变体您正在使用,它接受 Comparator
参数,需要某种引用类型的数组作为输入,因此您不能将原始数组传递给它。
因此你不能传递原始数组 A
到它。
您必须将原始数组 ( int[]
) 转换为引用类型数组 ( Integer[]
) 才能使用 void sort(T[] a, Comparator<? super T> c)
.
但是,您可以使用 Stream
来减少代码量s:
public int[] sortArrayByParity(int[] A) {
return Arrays.stream(A).boxed().sorted(Comparator.comparing(a -> a % 2)).mapToInt(Integer::intValue).toArray();
}
关于java - 为什么传递的数组不能使用lambda函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689137/