版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33960882/article/details/85111625
TreeSet集合石用来对象元素进行排序的,同样也具有保持元素唯一性的特征(通过实现Comparable接口)。
import java.io.Serializable;
public class Student implements Serializable, Comparable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
"}\n";
}
@Override
public int compareTo(Object o) {
if(!(o instanceof Student)){
throw new ClassCastException("object to cast student error !");
}
return this.age - ((Student)o).age;
}
}
import java.util.TreeSet;
public class Main {
public static void main(String []args){
TreeSet<Student> hs = new TreeSet<Student>();
for(int i = 0; i< 10; i++){
hs.add(new Student("AA"+i, 10));
}
System.out.println(hs);
}
}