Tôi phải sắp xếp Cuộc hẹn theo ngày giờ. Tôi có một ArrayList của cuộc hẹn và đã cố gắng tạo ra một so sánh để so sánh ngày tháng và thời gian của họ. Tôi đang cố gắng sử dụng phương thức Collections.sort, chuyển nó qua ArrayList của các cuộc hẹn và AppointmentComparator mà tôi đã tạo ra. Khi biên dịch tôi nhận được một "Không có phương pháp phù hợp để sắp xếp." Dưới đây là một liên kết đến thông báo lỗi đầy đủ tạo ra bởi trình biên dịch: http://prntscr.com/7y4qbSử dụng Bộ so sánh để đặt hàng ArrayList Java
sánh:
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 với lỗi cú pháp:
Collections.sort(book, new AppointmentComparator());
biến cuốn sách là một ArrayList của cuộc hẹn. ArrayList<Appointment>
AppointmentBook lớp:
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;
}
Bổ nhiệm lớp:
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;
}
}
Bạn có thể đăng toàn bộ lớp AppointmentComparator cho chúng tôi không? Có thể có một vấn đề trong định nghĩa lớp chính nó, và chúng ta chỉ có thể suy đoán mà không có một lỗi trình biên dịch/định nghĩa lớp chính nó. –
Bạn cũng có thể đăng cách bạn định nghĩa biến sách trước khi gọi Collections.sort() không? –
Ok được cập nhật để bao gồm toàn bộ lớp học – Legendish