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());
}
“数组”类定义在测试类的主要方法中。 为什么在我尝试反转数组时会出现编译错误?
最佳答案
Collections.reverseOrder()
返回 Comparator<Object>
.和 Arrays.sort
带有比较器不适用于原语
这应该可行
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());
}
}
关于java - 如何使用java以相反的顺序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5584579/