比较器Comparator与自定义排序

package com.yin2na.example; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class SortTest { public static void main(String[] args) { List list = new ArrayList(); list.add(new Student("yin2na", 24)); list.add(new Student("susanbear", 22)); list.add(new Student("doing", 20)); list.add(new Student("Jesus", 2011)); System.out.println("原顺序:"); for(Student stu : list) { System.out.println(stu); } System.out.println("默认顺序:"); Collections.sort(list); for(Student stu : list) { System.out.println(stu); } System.out.println("反序:"); Collections.sort(list, Collections.reverseOrder());//Collections.reverseOrder()返回一个比较器Comparator for(Student stu : list) { System.out.println(stu); } System.out.println("自定义顺序:"); Collections.sort(list, new Comparator(){//匿名内部类 public int compare(Student stu1, Student stu2) { if (stu1.getName().length() > stu2.getName().length()) { return 1; } else if (stu1.getName().length() < stu2.getName().length()) { return -1; } else { return 0; } } }); for(Student stu : list) { System.out.println(stu); } } } class Student implements Comparable { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int compareTo(Student stu) { if (this.age > stu.age) { return 1; } else if (this.age < stu.age) { return -1; } else { return 0; } } @Override public String toString() { return name + " is " + age; } }

你可能感兴趣的:(Java学习笔记)