對加入?TreeSet的Student對象實現Comparable接口,通過在Student中重寫compareTo()方法確定該對象在TreeSet中的排序方式
Student類如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class?Student?implements?Comparable
private?int?age;
//重寫compareTo()方法
public?int?compareTo(Object?o){
Student?s?=?(Student)?o;
if?(this.age?<?s.age?)
return?-1;
else?if(s.age?==?this.age)
return?0;
else
return?1;
}
當Student對象加入TreeSet時,是按年齡從小到大排序的。