import java.util.Set;
import java.util.TreeSet;
class Student implements Comparable{//必须实现接口
private Integer age;
public Student(Integer age) {
super();
this.age = age;
}
@Override
public int compareTo(Object o) {//比较的规则,运用泛型可以消除强转!
if(o instanceof Student){
Student s = (Student)o;
return this.age.compareTo(s.age);
}
return 0;
}
@Override
public String toString() {
return age+"" ;
}
}
public class Demo14 {
public static void main(String[] args) {
Set<Student> s = new TreeSet();
s.add(new Student(140));
s.add(new Student(15));
s.add(new Student(11));
s.add(new Student(63));
s.add(new Student(96));
System.out.println(s);//[11, 15, 63, 96, 140]
}
} |
|