天天看點

TreeSet --實作學生按年齡大小和姓名排序

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("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;  

<dl></dl>

<dd>比較此對象與指定對象的順序。如果該對象小于、等于或大于指定對象,則分别傳回負整數、零或正整數。</dd>

實作類必須確定對于所有的 x 和 y 都存在 sgn(x.compareto(y)) == -sgn(y.compareto(x)) 的關系。(這意味着如果 y.compareto(x)抛出一個異常,則 x.compareto(y) 也要抛出一個異常。)

實作類還必須確定關系是可傳遞的:(x.compareto(y)&gt;0 &amp;&amp; y.compareto(z)&gt;0) 意味着 x.compareto(z)&gt;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 中的一個值。

<dd></dd>

<dt>參數:</dt>

<code>o</code> - 要比較的對象。

<dt>傳回:</dt>

<dd>負整數、零或正整數,根據此對象是小于、等于還是大于指定對象。</dd>

<dt>抛出:</dt>

轉載:

http://blog.csdn.net/chaoyu168/article/details/49335977