在Java中,使用sort()方法可以對(duì)數(shù)組進(jìn)行排序,sort()方法有兩個(gè)重載的版本:一個(gè)對(duì)基本數(shù)據(jù)類(lèi)型數(shù)組進(jìn)行排序,一個(gè)對(duì)對(duì)象數(shù)組進(jìn)行排序。
sort()方法可以直接對(duì)基本數(shù)據(jù)類(lèi)型數(shù)組進(jìn)行升序排序,也可以通過(guò)傳入Comparator對(duì)象對(duì)數(shù)組進(jìn)行降序排序。
升序排序示例:
int[] arr = {5, 3, 1, 4, 2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // 輸出:[1, 2, 3, 4, 5]
降序排序示例:
int[] arr = {5, 3, 1, 4, 2};
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
System.out.println(Arrays.toString(arr)); // 輸出:[5, 4, 3, 2, 1]
對(duì)于對(duì)象數(shù)組,可以實(shí)現(xiàn)Comparable接口或者使用Comparator對(duì)象來(lái)指定排序規(guī)則。
實(shí)現(xiàn)Comparable接口示例:
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person o) {
return this.age - o.getAge(); // 按照年齡升序排序
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Person[] people = {
new Person("Alice", 20),
new Person("Bob", 18),
new Person("Charlie", 22)
};
Arrays.sort(people);
System.out.println(Arrays.toString(people)); // 輸出:[Person [name=Bob, age=18], Person [name=Alice, age=20], Person [name=Charlie, age=22]]
使用Comparator對(duì)象示例:
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p2.getAge() - p1.getAge(); // 按照年齡降序排序
}
}
Person[] people = {
new Person("Alice", 20),
new Person("Bob", 18),
new Person("Charlie", 22)
};
Arrays.sort(people, new AgeComparator());
System.out.println(Arrays.toString(people)); // 輸出:[Person [name=Charlie, age=22], Person [name=Alice, age=20], Person [name=Bob, age=18]]
以上就是對(duì)Java中sort()方法進(jìn)行數(shù)組排序的詳細(xì)解釋?zhuān)▽?duì)基本數(shù)據(jù)類(lèi)型數(shù)組和對(duì)象數(shù)組的升序和降序排序的示例。