欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

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

来源: javaer 分享于  点击 16482 次 点评:170

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;
    }
}

结果如下:

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

相关文章

    暂无相关文章

用户点评