java中TreeSet的Comparator比較器的三種使用方法

java中treeset使用Comparator進行比較的三種方法

1.讓元素具備比較性。
比如我們比較兩個人。我們定義一個person類,並且實現Comparable接口
例:
public class Person implements Comparable{
private int age;
private String name;

public Person(){}

public Person(int age, String name) {
    this.age = age;
    this.name = name;
}

public int getAge() {
    return age;
}

public String getName() {
    return name;
}

public void setAge(int age) {
    this.age = age;
}
public void setName(String name) {
    this.name = name;
}

@Override
public int compareTo(Object o) {
    if (!(o instanceof Person))
        throw new RuntimeException("不是人對象");
    Person p = (Person) o;
    if (this.age > p.age)
        return 1;
    if (this.age == p.age){
        return this.name.compareTo(p.name);
    }
    return -1;
}

}

2.第二種是寫個類實現Comparator接口
例:

     class myComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;

        int num = p1.getName().compareTo(p2.getName());
      // 0的話是兩個相同,進行下一個屬性比較
        if (num == 0){
            return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
        }

        return num;
    }
}

然後在new Set的時候放進去。如
TreeSet ts = new TreeSet(new myComparator());

3.第三種寫內名內部類方法如:

    TreeSet ts = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            Person p1 = (Person) o1;
            Person p2 = (Person) o2;

            int num = p1.getName().compareTo(p2.getName());

            if (num == 0){
                return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
            }

            return num;

        }
    });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章