import java.util.Comparator;import java.util.TreeSet;public class StudentTreeSet { public static void main(String[] args) { // TODO Auto-generated method stub TreeSet students = new TreeSet(new AgeAscComparator()); students.add(new Student("张三", 3,59)); //实参分别是name,age,score; students.add(new Student("李四", 1,60)); students.add(new Student("王五", 2,88)); students.add(new Student("陈六", 5,46)); students.add(new Student("田七", 4,55)); System.out.println(students); } }class AgeAscComparator implements Comparator{ @Override public int compare(Student o1, Student o2) { return o1.getAge()-o2.getAge(); } }
return o1.getAge()-o2.getAge();
按照对象的age,从小到大排序(如果要从大到小,就是o2-o1)