定制排序的一个例子

来源:互联网 发布:精雕软件视频教程 编辑:程序博客网 时间:2024/05/14 07:48

各种原理还不是很懂。先上代码:(下午研究下)

import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Scanner;import antlr.collections.List;public class Main{    public static void main(String[] args)    {        Scanner sc = new Scanner(System.in);        while (sc.hasNext())        {            int num = sc.nextInt();            ArrayList<time> li =  new ArrayList<time>(num);            for (int i = 0;i < num;i++)            {                li.add(new time(true,sc.nextInt()));                li.add(new time(false,sc.nextInt()));            }            Collections.sort(li);            System.out.println(li);        }    }}class time implements Comparable<time>{    boolean flag = false;    int timeValue = 0;    public time(boolean fg,int value)    {        this.flag = fg;        this.timeValue = value;    }    @Override    public String toString()    {        return "时间"+flag+"时间值"+timeValue;    }    public  int  com(time o)    {        if (timeValue > o.timeValue)        {            return 1;        }        else if(timeValue == o.timeValue  && (flag == false && o.flag == true))        {            return 1;        }        else if (timeValue == o.timeValue && (flag == true && o.flag == false))        {            return -1;        }        else if (timeValue == o.timeValue  && (o.flag == flag))        {            return 0;        }        else        {            return -1;        }    }    @Override    public int compareTo(time o) {        // TODO Auto-generated method stub        return com(o);    }}

运行结果如下:
3
1 3
2 3
3 4
[时间true时间值1, 时间true时间值2, 时间true时间值3, 时间false时间值3, 时间false时间值3, 时间false时间值4]

原创粉丝点击