可以使用java.util.Arrays.sort()方法对对象数组进行排序,并使用单个参数,即要排序的数组。演示此的程序如下所示-
import java.util.Arrays; public class Demo { public static void main(String args[]) throws Exception { String str[] = new String[]{"apple","orange","mango","guava", "melon"}; int n = str.length; System.out.println("The original array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } Arrays.sort(str); System.out.println("The sorted array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } } }
输出结果
字符串的原始数组是-
apple orange mango guava melon The sorted array of strings is: apple guava mango melon orange
现在让我们了解上面的程序。
首先定义字符串数组str,然后使用for循环打印。演示这的代码片段如下-
String str[] = new String[]{"apple","orange","mango","guava", "melon"}; int n = str.length; System.out.println("The original array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }
然后,使用Arrays.sort()方法对str进行排序。然后使用for循环显示结果排序后的字符串数组。演示这的代码片段如下-
Arrays.sort(str); System.out.println("The sorted array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }