JAVA中的Comparable介面和自定義比較器

2020-10-12 22:00:10

Java中的自然排序

自然排序

  • TreeSet集合在儲存資料時有一定的順序,它會將一些資料進行比較,比較呼叫的是comparaTo()方法,該方法是在Comparable中定義的,自然排序要求TreeSet集合中儲存的資料必須實現Comparable介面,並且重寫ComparaTo()方法
public class 自然排序 {
    public static void main(String[] args) {
        //定義一個TreeSet集合
        TreeSet treeSet = new TreeSet();
        Teacher t1 = new Teacher("Jack",19);
        Teacher t2 = new Teacher("King",20);
        Teacher t3 = new Teacher("Tom",19);
        Teacher t4 = new Teacher("Rose",20);
        treeSet.add(t1);
        treeSet.add(t2);
        treeSet.add(t3);
        treeSet.add(t4);
        System.out.println(treeSet);
    }
}
//定義Teacher類實現Comparable介面
class  Teacher implements Comparable{

    String name;
    int age;
    public Teacher(String name,int age){
        this.name = name;
        this.age = age;
    }
    //重寫toString方法
    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    //先比較年齡在比較名字
    @Override
    public int compareTo(Object o) {
        Teacher teacher = (Teacher)o;
        if (this.age > teacher.age){
            return 1;
        }
        if (this.age == teacher.age){
            return this.name.compareTo(teacher.name);
        }
        return -1;
    }
}
  • 執行結果
[Teacher{name='Jack', age=19}, Teacher{name='Tom', age=19}, Teacher{name='King', age=20}, Teacher{name='Rose', age=20}]

客製化排序

  • 如果單單使用ComparaTo()不能滿足要求,這時可以通過在建立TreeSet集合的時候就自定義一個比較器來對元素進行客製化排序
import java.util.Comparator;
import java.util.TreeSet;

public class 客製化排序 {
    public static void main(String[] args) {
        //在建立集合是傳入比較器
        TreeSet treeSet = new TreeSet(new MyComparable());
        treeSet.add("Jack");
        treeSet.add("Tom");
        treeSet.add("Helena");
        System.out.println(treeSet);
    }
}
//自定義的比較器
class MyComparable implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        //以單詞的長度來排序
        String s1 = (String)o1;
        String s2 = (String)o2;
        int resoult = s1.length() - s2.length();
        return resoult;
    }
}
  • 結果
[Tom, Jack, Helena]