public class Student implements Comparable {
String name;
int age
public int compareTo(Student another) {
int i = 0;
i = name.compareTo(another.name);
if(i == 0) {
return age - another.age;
} else {
return i;
}
}
}
這時我們可以直接用 Collections.sort( StudentList ) 對其排序了.(
**只需傳入要排序的列表**)
實現(xiàn)Comparator需要重寫 compare 方法
public class Student{
String name;
int age
}
class StudentComparator implements Comparator {
public int compare(Student one, Student another) {
int i = 0;
i = one.name.compareTo(another.name);
if(i == 0) {
return one.age - another.age;
} else {
return i; }
}
}
Collections.sort( StudentList , new StudentComparator()) 可以對其排序(
**不僅要傳入待排序的列表,還要傳入實現(xiàn)了Comparator的類的對象**)