英文:
I'm getting an error while sorting an array with the following code
问题
我能够获得这个输出:
    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,(a,b)->(b-a));
错误信息为:
    错误:     方法 Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) 不适用
我在这里漏掉了什么?
英文:
I am able to get output for this:
int arr[][]={{1,2},{2,3},{3,4},{1,3}};
Arrays.sort(arr,(a,b)->(b[0]-a[0]));
But it's showing error for this:
int arr[]={1,2,3,4,5,6};
Arrays.sort(arr,(a,b)->(b-a));
<!-- -->
Error:     method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
What am I missing here?
答案1
得分: 5
没有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)方法的签名。
英文:
There's no variant of Arrays.sort() that accepts an int[] and a Comparator, which is not surprising, given that you cannot define a Comparator<int> (generic type parameters must be reference types).
If you change your array to Integer[], it will work:
Integer[] arr={1,2,3,4,5,6};
Arrays.sort(arr,(a,b)->(b-a));
Your first snippet works because the element type of your first (2D) array is int[] (array of ints), and arrays are reference types. Therefore it fits the signature of the public static <T> void sort(T[] a, Comparator<? super T> c) method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论