xyvyre
xyvyre

Reputation: 175

Sorting an int array in descending order is giving "method not applicable for arguments"

I'm trying to sort an array in descending order in Java using this code:

for(int i = 0; i < arr.length; i++) {
   Comparator comparator = Collections.reverseOrder();
   Arrays.sort(arr,comparator);
}

But I get this error:

The method sort(int[]) in the type Arrays is not applicable for the arguments (int[], Comparator)

Upvotes: 4

Views: 7722

Answers (5)

CHANDRU R
CHANDRU R

Reputation: 143

Change int Integer while defining an array. Change int arr[]={}; to Integer arr[]={}; This will make your code to run

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

The only sort method that accepts a comparator in the Arrays class requires you to supply an object array. There is no method within the class with a signature of sort(int[], Comparator)

Upvotes: 0

basiljames
basiljames

Reputation: 4847

Arrays.sort(arr,comparator); will not work on primitives. The arr has to be array of Objects.

Upvotes: 0

assylias
assylias

Reputation: 328629

If you look at the javadoc of Arrays, you will see that the only sort methods that take a comparator as a second parameter are:

sort(T[] a, Comparator<? super T> c)
sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)

In your case, int[] is not a T[] (Integer[] would be) so you can't apply those methods.

You have (at least) 2 options:

  • sort in ascending order and reverse the array
  • transform the array into an Integer[] and use the methods above

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1500865

It's not clear why you're trying to loop, but the Arrays.sort methods operating on primitive arrays don't allow a custom comparator to be specified.

The simplest approach would be to sort and then reverse the array. I can't immediately find a reverse method which would take an int[] but it would be easy to write your own.

Upvotes: 1

Related Questions