用java.util.Collections中的sort方法對兩個類的物件進行排序

kevinBlogs發表於2018-01-02

這對標題提出的問題提供了一種比較笨的解決方案,採用了外部比較器介面Comparator。

import java.util.*;

class A implements Comparable<A> {
    int num;
    public A(int num){
        this.num = num;
    }
    @Override
    public int compareTo(A a){
        return this.num > a.num ? 1 : -1;
    }
    @Override
    public String toString(){
        return "A-"+ this.num;
    }
}

class B implements Comparable<B> {
    int num;
    public B(int num){
        this.num = num;
    }
    @Override
    public int compareTo(B b){
        return this.num > b.num ? 1 : -1;
    }
    @Override
    public String toString(){
        return "B-"+ this.num;
    }
}

class ABComparator implements Comparator {

    public int compare(Object o1, Object o2) {
        if((o1 instanceof A) && (o2 instanceof B)){
            A a = (A) o1;
            B b = (B) o2;
            if(a.num > b.num){
                return 1;
            } else {
                return -1;
            }
        }
        if((o1 instanceof B) && (o2 instanceof A)){
            B a = (B) o1;
            A b = (A) o2;
            if(a.num > b.num){
                return 1;
            } else {
                return -1;
            }
        }
        if((o1 instanceof A) && (o2 instanceof A)){
            A a = (A) o1;
            A b = (A) o2;
            return a.compareTo(b);
        }
        if((o1 instanceof B) && (o2 instanceof B)){
            B a = (B) o1;
            B b = (B) o2;
            return a.compareTo(b);
        }
        return 0;
    }
}

class Test1 {
    public static void main(String[] args) {
        List ls = new ArrayList();  
        ls.add(new A(1));
        ls.add(new A(15));
        ls.add(new A(20));
        ls.add(new A(4));
        ls.add(new A(13));

        ls.add(new B(11));
        ls.add(new B(14));
        ls.add(new B(12));
        ls.add(new B(13));
        ls.add(new B(10));

        Collections.sort(ls, new ABComparator());

        System.out.println(ls);
    }
}

相關文章