天天看點

TreeSet自定義類

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)//覆寫接口裡的compareTo方法,用Object 接收參數,不能聲明異常
    {
    if(!(obj instanceof Student))//先判斷obj是Student類的執行個體
        throw new RuntimeException("不是學生對象")//抛出運作時異常
    Student s = (Student)obj;//強轉s
 
    //System.out.println(this.name+"...compareto"+s.name)
    if (this.age>s.age)//調用者比較傳入參數,
        return 1;
    if (this.age==s.age)//如果年齡屬性相同,再調用名字屬性比較
    {
        return this.name.compareTo(s.name);//調用者 調用String類的comparTo方法 按字典順序比較 (傳入參數)
    }       
    if (this.age<s.age)
        return -1;  
    }
    public String getName()
    {
        return name;
    }
    public String getAge()
    {
        return Age;
    }   
}
 
class  TreeSetDemo2
{
    public static void main(String[] args) 
    {
        TreeSet ts = new TressSet(new MyCompare());//傳進比較器
        ts.add(new Student("lisi02",22));
        ts.add(new Student("lisi007",20));
        ts.add(new Student("lisi09",19));
        ts.add(new Student("lisi01",40));
 
        Iterator it = ts.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }
}
 
class MyCompare implements Comparator//定義比較器
{
    public int compare(Object o1,Object o2)
    {
        Student s1 = (Student)o1;
        Student s2 = (Student)o2;
        int num = s1.get.getName().compareTo(s2.getName());
        if(num == 0)
        {
            new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
            /*
            if(s1.getAge()>s2.getAge())
                return 1;
            if(s1.getAge()==s2.getAge())
                return 0;
            if(s1.getAge()<s2.getAge())
                return -1;
            */
        }
        return num;
    }
}      
上一篇: ESC使用體驗
下一篇: 多線程

繼續閱讀