Student类代码如下所示:
package com.test.Test10;public class Student implements Comparable<Student>{private int age;private String name;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Student(int age, String name) {this.age = age;this.name = name;}@Overridepublic String toString() {return "Student{" +"age=" + age +", name='" + name + '\'' +'}';}@Overridepublic int compareTo(Student o) {//return 0;return this.getAge()-o.getAge();} }测试类如下所示:
package com.test.Test10;import java.util.TreeSet;public class Test03 {public static void main(String[] args) {//创建一个TreeSetTreeSet<Student> ts = new TreeSet<>();ts.add(new Student(10,"elili"));ts.add(new Student(8,"blili"));ts.add(new Student(4,"alili"));ts.add(new Student(9,"clili"));ts.add(new Student(10,"elili"));ts.add(new Student(1,"dlili"));System.out.println(ts.size()); //放了6个数据,出来了5个,重复的删除了System.out.println(ts); //[Student{age=1, name='dlili'}, Student{age=4, name='alili'}, Student{age=8, name='blili'}, Student{age=9, name='clili'}, Student{age=10, name='elili'}]} }