我在使用以下代码对数组进行排序时遇到了一个错误:

huangapple go评论68阅读模式
英文:

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)-&gt;(b[0]-a[0]));

But it's showing error for this:

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

<!-- -->

Error:     method Arrays.&lt;T#1&gt;sort(T#1[],Comparator&lt;? super T#1&gt;) 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&lt;int&gt; (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)-&gt;(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 &lt;T&gt; void sort(T[] a, Comparator&lt;? super T&gt; c) method.

huangapple
  • 本文由 发表于 2020年8月16日 14:28:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63433821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定