I have Events class arraylist where Events class is like
class Events {
Date eventDate;
String eventType;
}
Now I want to sort this array based on the newest eventDate first. If two or more events are on the same date then I have sort them in following event type order
1. Maths 2. Science 3. History 4. Algebra
.
So if my list is
{ "01/01/2010 History", "01/01/2010 Algebra", "01/01/2010 Maths", "01/01/2010 Science"}
Then I want to sort it like
{ "01/01/2010 Maths", "01/01/2010 Science", "01/01/2010 History", "01/01/2010 Algebra"}
Please suggest how can I do this?
TIA, Hanumant.
Not tested, but it should give you the idea:
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;
}
}
Your design leaves a little something to be desired. Try:
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;
}
}
Then given a Collection<Event> events
you can just Collections.sort(events)
.
因为这听起来像HW,你应该为Events类实现Comparable接口。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.