Comparator定义的比较器,对一组对象进行排序代码如下:
package com.array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @from www.ityuan.com
* @Description: 使用Comparator定义一个比较器,对一组学生对象,根据年龄从小到大排序
*/
class Student {
private Integer age;
private String name;
public Student(Integer age, String name) {
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class StudentComparator implements Comparator{
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
}
public class ComparatorSort {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Student(30, "student30"));
list.add(new Student(40, "student40"));
list.add(new Student(10, "student10"));
list.add(new Student(20, "student20"));
Collections.sort(list, new StudentComparator());
for (Student s : list) {
System.out.println(s.getName());
}
}
}
执行结果如下:
student10
student20
student30
student40