public class Student implements Comparable<Student>{
private Integer no;
private String name;
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Student o) {
return (this.no - o.getNo());
}
public Student(Integer no, String name) {
this.no = no;
this.name = name;
}
}
import java.util.Comparator;
public class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return (o1.getNo() - o2.getNo());
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestCompare {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student(3, "3"));
list.add(new Student(2, "2"));
list.add(new Student(1, "1"));
// 相当于外部比较器
list.sort(new StudentComparator());
System.out.println("comparator");
for(Student s : list) {
System.out.println(s.getName());
}
// 相当于内部比较器
System.out.println("comparable");
list.add(new Student(6, "6"));
list.add(new Student(5, "5"));
list.add(new Student(4, "4"));
System.out.println("sort before");
for(Student s : list) {
System.out.println(s.getName());
}
System.out.println("sort after");
Collections.sort(list);
for(Student s : list) {
System.out.println(s.getName());
}
}
}