Reputation: 175
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
Reputation: 143
Change int Integer while defining an array.
Change int arr[]={};
to Integer arr[]={};
This will make your code to run
Upvotes: 1
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
Reputation: 4847
Arrays.sort(arr,comparator);
will not work on primitives. The arr
has to be array of Objects.
Upvotes: 0
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:
Integer[]
and use the methods aboveUpvotes: 9
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