1 回答

TA貢獻1802條經(jīng)驗 獲得超5個贊
我給你看個例子你就知道了
這里有一個Person類,里面有firstName and surename2個成員。你的類要實現(xiàn)那個Comparable接口。然后在compareTo函數(shù)里決定如果排序,在這個例子里是按照surename排序,surename相同的就按照firstName排序的。
希望這個例子對你了解自定義的排序有幫助。
import java.util.Arrays;
class Person implements Comparable<Person> {
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
public String toString() {
return firstName + " " + surname;
}
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;
}
private String firstName;
private String surname;
}
public class MainClass {
public static void main(String[] args) {
Person[] authors = { new Person("A", "B"),
new Person("C", "D"),
new Person("E", "F"),
new Person("Z", "Y"),
new Person("X", "T"),
new Person("O", "R") };
Arrays.sort(authors);
System.out.println("\nThe cast is ascending sequence is:\n");
for (Person person : authors) {
System.out.println(person);
}
}
}
對于你提到的那個問題,你可以去看卡你 Arrays.sort(a)的代碼。
添加回答
舉報