代码如下:
package ComparablePack;public class Student implements Comparable<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;}@Overridepublic int compareTo(Student s) {int num = this.age-s.age;int num2 = num==0?this.name.compareTo(s.name):num;return num2;}
}
package ComparablePack;import java.util.TreeSet;public class TreeSetDemo01 {public static void main(String[] args){TreeSet<Student> ts = new TreeSet<Student>();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());}}}