实现比较器(Comparator)接口
实现比较器例子:
package ArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
class ArrayListTest {
public static void printElements(Collection<?> c) {
Iterator<?> it = c.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
public static void main(String[] args) {
Student s1 = new Student(5, "xiaoxi");
Student s2 = new Student(2, "xiaohong");
Student s3 = new Student(3, "xiaozhu");
ArrayList<Student> al = new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
// Collections类进行排序
Collections.sort(al, new Student.StudentComparator());
printElements(al);