天天看點

TreeSet的兩種排序方法

treeset的兩種排序方法:自然排序和定義比較器,推薦使用定義比較器方法。

<span style="color:#333333;">import java.util.*;  

class treeset   

{  

    public static void main(string[] args)   

    {  

        treeset t = new treeset();  

//      treeset t = new treeset(new mycomparator());//第二種方法定義  

        t.add(new student("a1",18));  

        t.add(new student("a2",18));  

        t.add(new student("a3",16));  

        t.add(new student("a4",25));  

        for(iterator it = t.iterator();it.hasnext();)  

        {  

            student s = (student)it.next();  

            sop(s.getname()+","+s.getage());  

        }  

    }  

    public static void sop(object obj)  

        system.out.println(obj);  

}  

/* 

自然排序法 定義comparable接口,覆寫compareto方法 

*/  

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 s = (student)obj;  

        if(this.age>s.age)  

            return 1;  

        if(this.age==s.age)  

            return this.name.compareto(s.name);  

        return -1;  

    public string getname()  

        return name;  

    public int getage()  

        return age;  

定義比較器   當兩種方法都存在時,以比較器為主。 

定義一個類,實作comparator接口,覆寫compare方法 

class mycomparator implements comparator  

    public int compare(object o1,object o2)  

        student s1 = (student)o1;  

        student s2 = (student)o2;  

        int num = s1.getname().compareto(s2.getname());  

        if(num ==0)  

            if(s1.getage()>s2.getage())  

                return 1;  

            if(s1.getage()==s2.getage())  

                return 0;  

            return -1;  

        return num;  

}</span>  

轉載:http://blog.csdn.net/chaoyu168/article/details/49339771