在Java中对对象数组进行排序
可以使用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]);
}热门推荐
3 年月日祝福语简短
5 送蛇的祝福语简短
10 Q穷人结婚祝福语简短
11 弟弟生日祝福语简短的话
12 婚礼祝福语简短精辟的
13 元旦的祝福语简短 公司
14 学生节祝福语大全简短
15 生日祝福语简短独特的
16 祝女性生日祝福语简短
17 官宣新年祝福语简短
18 写给老师祝福语简短大学