本文實(shí)例講述了Java TreeSet實(shí)現(xiàn)學(xué)生按年齡大小和姓名排序的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import java.util.*; class Treeset { public static void main(String[] args) { TreeSet t = new TreeSet(); t.add( new student( "a1" , 15 )); t.add( new student( "a2" , 15 )); t.add( new student( "a1" , 15 )); t.add( new student( "a3" , 16 )); t.add( new student( "a3" , 18 )); for (Iterator it = t.iterator();it.hasNext();) { student tt = (student)it.next(); //強(qiáng)制轉(zhuǎn)成學(xué)生類(lèi)型 sop(tt.getName()+ "," +tt.getAge()); } } public static void sop(Object obj) { System.out.println(obj); } } class student implements Comparable //接口讓學(xué)生具有比較性 { private String name; private int age; student(String name, int age) { this .name = name; this .age = age; } public int compareTo(Object obj) { if (!(obj instanceof student)) throw new RuntimeException( "不是學(xué)生" ); student t = (student)obj; if ( this .age > t.age) return 1 ; if ( this .age==t.age) return this .name.compareTo(t.name); //如果年齡相同,在比較姓名排序 return - 1 ; } public String getName() { return name; } public int getAge() { return age; } } |
compareTo
int compareTo(T o)
比較此對(duì)象與指定對(duì)象的順序。如果該對(duì)象小于、等于或大于指定對(duì)象,則分別返回負(fù)整數(shù)、零或正整數(shù)。
實(shí)現(xiàn)類(lèi)必須確保對(duì)于所有的 x 和 y 都存在 sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) 的關(guān)系。(這意味著如果 y.compareTo(x)
拋出一個(gè)異常,則 x.compareTo(y)
也要拋出一個(gè)異常。)
實(shí)現(xiàn)類(lèi)還必須確保關(guān)系是可傳遞的:(x.compareTo(y)>0 && y.compareTo(z)>0) 意味著 x.compareTo(z)>0。
最后,實(shí)現(xiàn)者必須確保 x.compareTo(y)==0 意味著對(duì)于所有的 z,都存在 sgn(x.compareTo(z)) == sgn(y.compareTo(z))。 強(qiáng)烈推薦 (x.compareTo(y)==0) == (x.equals(y)) 這種做法,但并不是 嚴(yán)格要求這樣做。一般來(lái)說(shuō),任何實(shí)現(xiàn) Comparable 接口和違背此條件的類(lèi)都應(yīng)該清楚地指出這一事實(shí)。推薦如此闡述:“注意:此類(lèi)具有與 equals 不一致的自然排序。”
在前面的描述中,符號(hào) sgn(expression)
指定 signum 數(shù)學(xué)函數(shù),該函數(shù)根據(jù) expression 的值是負(fù)數(shù)、零還是正數(shù),分別返回 -1、0 或 1 中的一個(gè)值。
參數(shù):
o - 要比較的對(duì)象。
返回:
負(fù)整數(shù)、零或正整數(shù),根據(jù)此對(duì)象是小于、等于還是大于指定對(duì)象。
拋出:
ClassCastException - 如果指定對(duì)象的類(lèi)型不允許它與此對(duì)象進(jìn)行比較。
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.csdn.net/chaoyu168/article/details/49335977