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?
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With