在 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]);
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP