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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.