java中将一个字符串数组按字典序重新排列。高手帮忙解决一下,谢谢!

如题所述

import java.util.Arrays;
public class Test{
public static void mian(String[] args){
String sr[] = {"爪哇","汇编","计算机","键盘","鼠标"};
Arrays.sort(sr);
for(int i=0;i<sr.length;i++){
System.out.println(sr[i]);
}
}
}
楼主是这个吧?
引入:import java.util.Arrays;
方法:Arrays.sort(数组名);
可以实现对数组按字典顺序排序.....
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-03-08
大小写怎么考虑排序?
import java.util.Arrays;

public class Test {

public static void main(String[] args) {

String[] ary = {"test", "abc", "apple", "PEar"};

System.out.println("Before sorted, the array is: " + Arrays.toString(ary));

Arrays.sort(ary);

System.out.println("After sorted, the new array is: " + Arrays.toString(ary));

}

}追问

您这这个程序是区分了大小写,先把大写按照字典排序,然后再排小写,如果按照字典那样,不区分大小写,应该怎样排序呢?

追答

import java.util.Arrays;
import java.util.Comparator;

public class Test {

public static void main(String[] args) {

String[] ary = {"test", "abc", "apple", "PEar", "AB"};

System.out.println("Before sorted, the array is: " + Arrays.toString(ary));

Arrays.sort(ary, new Comparator(){

public int compare(String o1, String o2) {
String[] temp = {o1.toLowerCase(), o2.toLowerCase()};
Arrays.sort(temp);

if(o1.equalsIgnoreCase(temp[0])){
return -1;
}else if(temp[0].equalsIgnoreCase(temp[1])){
return 0;
}else{
return 1;
}

}

});

System.out.println("After sorted, the new array is: " + Arrays.toString(ary));

}

}

-------testing
Before sorted, the array is: [test, abc, apple, PEar, AB]
After sorted, the new array is: [AB, abc, apple, PEar, test]

本回答被网友采纳
相似回答