本文實例講述了Java TreeSet實現學生按年齡大小和姓名排序的方法。分享給大家供大家參考,具體如下:
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(); //強制轉成學生類型 sop(tt.getName()+ "," +tt.getAge()); } } public static void sop(Object obj) { System.out.println(obj); } } class student implements Comparable //接口讓學生具有比較性 { 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( "不是學生" ); 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)
比較此對象與指定對象的順序。如果該對象小于、等于或大于指定對象,則分別返回負整數、零或正整數。
實現類必須確保對于所有的 x 和 y 都存在 sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) 的關系。(這意味著如果 y.compareTo(x)
拋出一個異常,則 x.compareTo(y)
也要拋出一個異常。)
實現類還必須確保關系是可傳遞的:(x.compareTo(y)>0 && y.compareTo(z)>0) 意味著 x.compareTo(z)>0。
最后,實現者必須確保 x.compareTo(y)==0 意味著對于所有的 z,都存在 sgn(x.compareTo(z)) == sgn(y.compareTo(z))。 強烈推薦 (x.compareTo(y)==0) == (x.equals(y)) 這種做法,但并不是 嚴格要求這樣做。一般來說,任何實現 Comparable 接口和違背此條件的類都應該清楚地指出這一事實。推薦如此闡述:“注意:此類具有與 equals 不一致的自然排序。”
在前面的描述中,符號 sgn(expression)
指定 signum 數學函數,該函數根據 expression 的值是負數、零還是正數,分別返回 -1、0 或 1 中的一個值。
參數:
o - 要比較的對象。
返回:
負整數、零或正整數,根據此對象是小于、等于還是大于指定對象。
拋出:
ClassCastException - 如果指定對象的類型不允許它與此對象進行比較。
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/chaoyu168/article/details/49335977