Java中,经过使用Collections.sort对ArrayList进行排序

排序一个java中的结构体,直接上代码:

import java.util.*;

public class Main {
    public static Comparator<P> comp = new Comparator<P>(){
        public int compare(P p, P t1){
            if(p.a!=t1.a){
                return p.a>t1.a ? 1:-1;
            }
            else{
                return p.b>t1.b ? 1:-1;
            }
        }
    };
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        ArrayList<P> p = new ArrayList<P>();
        p.add(new P(2,1));
        p.add(new P(1,3));
        p.add(new P(2,3));

        System.out.println("排序前:");
        for (P x:p){
            System.out.println(x.a+" "+x.b);
        }
        System.out.println("排序后:");
        Collections.sort(p, comp);
        /* //这个和上面一句效果同样 Collections.sort(p, new Comparator<P>() { @Override public int compare(P p, P t1) { if (p.a!=t1.a){ return p.a>t1.a?1:-1; } else return p.b>t1.b?1:-1; } }); */
        for (P x:p){
            System.out.println(x.a+" "+x.b);
        }
    }
}
class P{
    int a;
    int b;
    P(int _a, int _b){
        this.a = _a;
        this.b = _b;
    }
}

结果以下:java

排序前:
2 1
1 3
2 3
排序后:
1 3
2 1
2 3