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)