I have a Task object that has a name and a date. The date value must be a String
. An example is 11/9/2015 23:00
to be compared to 11/24/2015 12:00
.
I need help writing a compareTo()
for this so that the task with the soonest date is displayed first. What I have is incorrect as it does not compare correctly. I know there are alternatives but it is required I do this with String. I have considered using .split()
to break up mm/dd/yyyy by "/"
but not sure how to do this.
public class Task implements Comparable<Task> {
/** Task name. */
private String name;
/** Task due date. */
private String dueDate;
/**
* Initializes a tasks name and due date.
* @param n Name
* @param d due date
*/
public Task(String n, String d) {
name = n;
dueDate = d;
}
/**
* Accessor for task name.
* @return Task name.
*/
public String getName() {
return name;
}
/**
* Accessor for task due date.
* @return Task due date.
*/
public String getDueDate() {
return dueDate;
}
/**
* Compares the due dates of the tasks to get the soonest to the front of the list.
* @param t The task to compare.
* @return The tasks in chronological order.
*/
@Override
public int compareTo(Task t) { //Need help here.
int val = dueDate.compareTo(t.getDueDate());
if(val == 0) {
val = name.compareTo(t.getName());
}
if(dueDate.compareTo(t.getDueDate()) > 0) {
val = -1;
}
if(dueDate.compareTo(t.getDueDate()) < 0) {
val = 1;
}
return val;
}