Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array in reverse order using java?

Tags:

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 defiend in a main method of a testing class. why does it give me a compile error when I try reversing the array?

like image 756
Aaron Avatar asked Feb 24 '23 14:02

Aaron


1 Answers

Collections.reverseOrder() returns a Comparator<Object>. And Arrays.sort with comparator doesn't 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());                            
    }
}
like image 170
Aravindan R Avatar answered Feb 27 '23 05:02

Aravindan R