I have to order Appointments by date and time. I have an ArrayList of Appointments and have tried to create a comparator to compare their dates and times. I am trying to use the Collections.sort method, passing it the ArrayList of Appointments and the AppointmentComparator I have created. When compiling I get a "No suitable method for sort." Here's a link to the full error message generated by the compiler : http://prntscr.com/7y4qb
Comparator:
public class AppointmentComparator implements Comparator<Appointment>
{
public int compare(Appointment a, Appointment b)
{
if (a.getDay() < b.getDay())
return -1;
if (a.getDay() == b.getDay())
{
if (a.getStart() < b.getStart())
return -1;
if (a.getStart() > b.getStart())
return 1;
return 0;
}
return 1;
}
Line with syntax error:
Collections.sort(book, new AppointmentComparator());
variable book is an ArrayList of Appointments. ArrayList<Appointment>
AppointmentBook class:
import java.util.ArrayList;
import java.util.Collections;
public class AppointmentBook
{
private ArrayList<Appointment> book;
public AppointmentBook()
{
book = new ArrayList<Appointment>();
}
public void addAppointment(Appointment appt)
{
book.add(appt);
Collections.sort(book, new AppointmentComparator());
}
public String printAppointments(int day)
{
String list = "";
for (int i = 0; i < book.size(); i++)
{
if (book.get(i).getDay() == day)
{
list = list + "Appointment description: " + book.get(i).getDescription() + "\n" + "Date of Appointment: " +
book.get(i).getDay() + "\n" + "Time: " + book.get(i).getStart() + " - " + book.get(i).getEnd() + "\n" + "\n";
}
}
return list;
}
Appointment class:
public class Appointment
{
private String desc;
private int day; //in format mmddyyyy
private int start; //in format hhmm
private int end; //in format hhmm
public Appointment(String description, int aptDay, int startTime, int endTime)
{
desc = description;
day = aptDay;
start = startTime;
end = endTime;
}
public String getDescription()
{
return desc;
}
public int getDay()
{
return day;
}
public int getStart()
{
return start;
}
public int getEnd()
{
return end;
}
}
From the error message it looks like you forgot to declare your comparator as implementing the interface:
public class AppointmentComparator implements Comparator<Appointment> {}
It needs to have the implements part, not just contain the method.
You need to cast your new AppointmentComparator
Collections.sort(book, new (Comparator)AppointmentComparator());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With