标签:java other another lan 覆盖 tor pre function return
实现Comparable接口要覆盖compareTo方法, 在compareTo方法里面实现比较
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 ) 对其排序了.(
**只需传入要排序的列表**)
实现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()) 可以对其排序(
**不仅要传入待排序的列表,还要传入实现了Comparator的类的对象**)
标签:java other another lan 覆盖 tor pre function return
原文地址:http://www.cnblogs.com/zhengxingpeng/p/6682656.html