Comparable实例

作者在 2010-05-21 10:27:40 发布以下内容


import java.util.TreeSet;
import java.util.Iterator;

public class TestComparable{
    public static void main(String[] args) {
        TreeSet ts = new TreeSet();
        ts.add(new Person(1003,"张三",15));
        ts.add(new Person(1008,"李四",25));
        ts.add(new Person(1015,"王五",73));
        ts.add(new Person(1001,"赵六",49));

        Iterator it = ts.iterator();
        while(it.hasNext()){
            Person employee = (Person)it.next();
            System.out.println(employee);    
        }
    }
}
public class Person implements java.lang.Comparable{
    private final int id;
    private String name;
    private int age;
    
    public Person(int id,String name,int age){
        this.id = id;
        this.name = name;
        this.age = age;    
    }
    public int getId(){
        return id;    
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;    
    }
    public void setAge(int age){
        this.age = age;    
    }
    public int getAge(){
        return age;    
    }
    public String toString(){
        return "Id: " + id + "\tName: " + name + "\tAge: " + age;    
    }    
    public int compareTo(Object o){
        Person p = (Person)o;
        return this.id - p.id;        
    }
    public boolean equals(Object o){
        boolean flag = false;
        if(o instanceof Person){
            if(this.id == ((Person)o).id)
                flag = true;
        }
        return false;        
    }    
}
集合 | 阅读 1117 次
文章评论,共1条
wtuaimmmm(作者)
2010-06-03 14:38
1
TreeSet采用自动排序的功能的时候才会使用,一般用HashSet
游客请输入验证码
浏览290824次