Java codeclass StudentComparator implements Comparator {
public int compare(Student o1, Student o2) {
return (o1.age < o2.age ? -1 : (o1.age == o2.age ? 0 : 1));
}
}
public class testSort {
public static void main(String[] args) {
Student stu1 = new Student("zhangsan", 18);
Student stu2 = new Student("lisi", 20);
Student stu3 = new Student("wangba", 31);
Student stu4 = new Student("zhaoliu", 17);
List stu = new ArrayList();
stu.add(stu1);
stu.add(stu2);
stu.add(stu3);
stu.add(stu4);
System.out.println("原始数据:");
for (Student student : stu) {
System.out.println(student);
}
System.out.println("进行排序......");
StudentComparator studentComparator=new StudentComparator();
Collections.sort(stu, studentComparator);
for (Student student : stu) {
System.out.println(student);
}
Student maxstu = Collections.max(stu,studentComparator);
System.out.println(maxstu);
}
}