代码如下:
package ComparablePack;public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
package ComparablePack;import java.util.Comparator;
import java.util.TreeSet;public class TreeSetDemo01 {public static void main(String[] args){TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {@Overridepublic int compare(Student s1, Student s2) {int num = s1.getAge()-s2.getAge();int num2 = num==0?s1.getName().compareTo(s2.getName()):num;return num2;}});Student s1 = new Student("Tom",13);Student s2 = new Student("Jack",17);Student s3 = new Student("Lily",29);Student s4 = new Student("Jbck",17);Student s5 = new Student("Jack",17);ts.add(s1);ts.add(s2);ts.add(s3);ts.add(s4);ts.add(s5);for (Student s:ts){System.out.println(s.getName()+","+s.getAge());}}}