1 import java.util.Arrays;
2 import java.util.Comparator;
3
4 class ResStrSort{
5 public static void main(String[] args) {
6 String strs[] = {"dog","cat","horse","cow"};
7 System.out.println("Initial order: ");
8 for(String s:strs) {
9 System.out.print(s + " ");
10 }
11 System.out.println();
12
13 ResStrComp rsc = new ResStrComp();
14 //将数组 与 比较器传递给Arrays.sort();
15 Arrays.sort(strs, rsc);
16 System.out.println("Sorted in reverse order: ");
17 for(String s:strs){
18 System.out.print(s + " ");
19 }
20 System.out.println();
21
22 Arrays.sort(strs);
23 System.out.println("Sirted in natural order: ");
24 for(String s:strs){
25 System.out.print(s + " ");
26 }
27 System.out.println();
28 }
29 }
30 /**
31 * Comparator是泛型接口
32 */
33 class ResStrComp implements Comparator<String>{
34
35 @Override
36 public int compare(String o1, String o2) {
37 return o2.compareTo(o1);//关键所在
38 }
39
40 }
字符串数组逆序
时间: 2024-10-22 00:35:27