Java 中对字符串数组排序有三种方法:使用 Arrays.sort() 进行快速排序、使用 Collections.sort() 进行归并排序、使用自定义比较器进行排序。
Java 中对字符串数组进行排序
字符串数组排序
在 Java 中,可以使用多种方法对字符串数组进行排序。
1. Arrays.sort()
- 该方法使用快速排序算法对给定的字符串数组进行原位排序。
- 语法:
Arrays.sort(arrayName)
2. Collections.sort()
- 该方法使用归并排序算法对给定的字符串数组进行排序。
- 语法:
Collections.sort(listName)
3. Comparator 接口
- 该方法使用自定义的比较器对字符串数组进行排序。
-
语法:
Arrays.sort(arrayName, new Comparator
() { @Override public int compare(String s1, String s2) { // 定义比较逻辑 } });
示例
// 使用 Arrays.sort() 对字符串数组进行升序排序
String[] names = {"John", "Mary", "Bob", "Alice"};
Arrays.sort(names);
// 使用 Collections.sort() 对字符串数组进行降序排序
List cities = Arrays.asList("London", "Paris", "New York", "Tokyo");
Collections.sort(cities, Coll
ections.reverseOrder());
// 使用 Comparator 接口按字符串长度排序
Arrays.sort(names, new Comparator() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});

ections.reverseOrder());
// 使用 Comparator 接口按字符串长度排序
Arrays.sort(names, new Comparator






