基于值顺序的Java排序对象列表(例如d,s,a,q,c)

时间:2011-02-02 08:12:50

标签: java sorting arraylist

我有Events类arraylist,其中Events类就像

class Events {
Date eventDate;
String eventType;
}

现在我想先根据最新的eventDate对这个数组进行排序。如果两个或多个事件在同一天,那么我按照以下事件类型顺序对它们进行排序

1. Maths 2. Science 3. History 4. Algebra

所以,如果我的名单是

{ "01/01/2010  History", "01/01/2010 Algebra", "01/01/2010 Maths", "01/01/2010 Science"}

然后我想把它排序为

{ "01/01/2010  Maths", "01/01/2010 Science", "01/01/2010 History", "01/01/2010 Algebra"}

请建议我该怎么做?

TIA, Hanumant。

4 个答案:

答案 0 :(得分:1)

您需要按照Comparator所示实现自己的here

答案 1 :(得分:1)

未经测试,但它应该给你一个想法:

class Events
implements Comparable
{
    Date eventDate;
    String eventType;

    int eventScore()
    {
        if (eventType.equals("Maths"))
            return 0;
        else if (eventType.equals("Science"))
            return 1;
        else if (eventType.equals("History"))
            return 2;
        else if (eventType.equals("Alegbra"))
            return 3;
        return 4;
    }

    public int compareTo(Object o)
    {
        Events other = (Events)o;
        if (other.eventDate.before(this.eventDate))
            return -1;
        else if (other.eventDate.after(this.eventDate))
            return 1;
        return other.eventScore() < this.eventScore() ? -1 : 1;
    }
}

答案 2 :(得分:1)

您的设计留下了一些不足之处。尝试:

class Event implements Comparable {
    private Date date;
    private Event.Type type;

    enum Type {
        MATHS,     // MATH / MATHEMATICS?
        SCIENCE,
        HISTORY,
        ALGEBRA
    }

    public int compareTo(Event other) {
        int comparison = other.date.compareTo(date);
        if (0 == comparison) {
            comparison = type.compareTo(other.type);
        }
        return comparison;
    }
}

然后给出Collection<Event> events,你可以Collections.sort(events)

答案 3 :(得分:0)

因为这听起来像是HW,你应该为Events类实现Comparable接口。