提问人:Aaron 提问时间:4/8/2011 最后编辑:Aaron 更新时间:8/22/2012 访问量:13555
如何使用 java 以相反的顺序对数组进行排序?
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());
}
“MyArray”类在测试类的 Main 方法中是 defiend 的。 为什么当我尝试反转数组时它给我一个编译错误?
答:
0赞
krookedking
4/8/2011
#1
你忘了申报haa = hello.getChars(0, hello_len, hello_array, 0);
-1赞
ewan.chalmers
4/8/2011
#2
HAA 未在您向我们展示的代码中定义。这是一个编译错误。
评论
0赞
Aaron
4/8/2011
好的,我已经修复了代码中的拼写错误,但它仍然给我一个错误?
2赞
Jeff Foster
4/8/2011
#3
我得到的错误(假设原始帖子有一些拼写错误)是返回一个.Collections.reverseOrder()
Comparator<Object>
Arrays.sort
(带有 compartor)仅为 Object 的后代定义,因此不适用于基元类型。
6赞
Aravindan R
4/8/2011
#4
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());
}
}
0赞
jtahlborn
4/8/2011
#5
使用 Arrays.sort 按升序排序,然后反转数组的元素(可以通过简单的循环内联完成)。
0赞
Jagadeesh
8/22/2012
#6
首先是代码没有遵循JAVA语言的标准。 类名应始终以大写字母开头,并且 Arrays 的 sort() 不应将原始值列表作为参数。将“char”更改为“Character”,然后使用 Arrays.sort 方法
评论
haa