Toshik Langade
Toshik Langade

Reputation: 812

I'm getting an error while sorting an array with the following code

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?

Upvotes: 1

Views: 75

Answers (1)

Eran
Eran

Reputation: 393781

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.

Upvotes: 5

Related Questions