在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]);
}热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便