How to sort an array in reverse order using java?

package javaLearning; import java.util.Arrays; import java.util.Collections; public class myarray { public static void name() { String hello; hello = "hello, world"; int hello_len = hello.length(); char[] hello_array = new char[hello_len]; hello.getChars(0, hello_len, hello_array, 0); Arrays.sort(hello_array, Collections.reverseOrder()); } 

the "myarray" class is defined by the main method of the test class. why does this give me a compilation error when i try to modify an array?

+4
source share
6 answers

Collections.reverseOrder() returns a Comparator<Object> . And Arrays.sort with a comparator does not work for primitives

This should work

 import java.util.Arrays; import java.util.Collections; public class MyArray { public static void name() { String hello = "hello, world"; char[] hello_array = hello.toCharArray(); // copy to wrapper array Character[] hello_array1 = new Character[hello_array.length]; for (int i = 0; i < hello_array.length; i++) { hello_array1[i] = hello_array[i]; } // sort the wrapper array instead of primitives Arrays.sort(hello_array1, Collections.reverseOrder()); } } 
+6
source

The error I get (assuming the original entry had some typos) is that Collections.reverseOrder() returns a Comparator<Object> .

Arrays.sort (with compartor) is defined only for descendants of Object, therefore it does not work for primitive types.

+2
source

You forgot to declare haa = hello.getChars(0, hello_len, hello_array, 0);

0
source

haa is not defined in the code you showed us. This is a compilation error.

0
source

Use Arrays.sort to sort in ascending order, then undo the elements of the array (you can do inline with a simple loop).

0
source

Firstly, the code does not comply with the JAVA language standards. The class name should always begin with the case of UPPER, and sort () Arrays should not accept a primitive list of values โ€‹โ€‹as a parameter. change "char" to "Character" and then use the Arrays.sort method

0
source

Source: https://habr.com/ru/post/1347133/


All Articles