Array Sorting Descending Order
Solution 1
There's no sort
method in Arrays
class that accepts an int[]
and a Comparator
. The sort
methods in the Arrays
class that accept a Comparator
require an array of reference type (while an int[]
is an array of a primitive type).
If you change the type of your scores
array from int[]
to Integer[]
, your code will work, since the method public static <T> void sort(T[] a, Comparator<? super T> c)
of the Arrays
class will match your Arrays.sort(scores, Collections.reverseOrder());
call.
final int EXAMS = 5;
Integer[] scores = new Integer [EXAMS]; // the only required change
for (int index = 0; index < EXAMS; index++) {
System.out.println("Enter the score for " + (index+1) +":");
scores[index] = kb.nextInt();
if (scores[index] < 0){
System.out.println("The number you have entered is invalid.");
scores[index] = kb.nextInt();
}
}
Arrays.sort(scores, Collections.reverseOrder());
System.out.println("The sorted int array is:");
for (int number : scores) {
System.out.println("Number = "+ number);
}
Solution 2
The following works (using the Integer
Objects instead of primitive int
):
Integer[] test = {1, 2, 4, 3, 5};
Arrays.sort(test, Collections.reverseOrder());
System.out.println(Arrays.toString(test)); // [5, 4, 3, 2, 1]
Solution 3
Collections.reverseOrder()
Won't work because the array is of primitive type. You can change from int to Integer or try something different like:
Arrays.sort(scores);
ArrayUtils.reverse(scores);
Your final option would be to make your own code.
Solution 4
You just need to change your array type from Primitive type
to Primitive wrapper class
i.e. int[] scores = new int [EXAMS]
to Integer[] scores = new Integer[EXAMS]
Arrays.sort
accept wrapper array in the first argument not primitive.
Hugo Diaz
Updated on June 04, 2022Comments
-
Hugo Diaz almost 2 years
I'm a new programmer to java, been using this website a lot to learn the ways. Today I've stumbled into another problem towards a program I'm doing for practice.
I have an array:
final int EXAMS = 5; int[] scores = new int [EXAMS];
The values for this array are then asked from the user through a Scanner object:
for (int index = 0; index < EXAMS; index++) { System.out.println("Enter the score for " + (index+1) +":"); scores[index] = kb.nextInt(); if (scores[index] < 0){ System.out.println("The number you have entered is invalid."); scores[index] = kb.nextInt(); } }
I managed to make an ascending order sorting of the values "scores[]":
Arrays.sort(scores); System.out.println("The sorted int array is:"); for (int number : scores) { System.out.println("Number = "+ number); }
But I want the sorting to be in descending order. When I put the
Arrays.sort(scores, Collections.reverseOrder());
I get an error saying: "no suitable method found for sorting." Please help.