Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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)

like image 375
xyvyre Avatar asked Oct 30 '25 00:10

xyvyre


1 Answers

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
like image 126
assylias Avatar answered Nov 01 '25 16:11

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!