使用 Comparator 排序 ArrayList Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10082123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:31:58  来源:igfitidea点击:

Using Comparator to order ArrayList Java

javasortingarraylistcomparator

提问by shaanIQ

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

我必须按日期和时间订购约会。我有一个约会的 ArrayList,并尝试创建一个比较器来比较它们的日期和时间。我正在尝试使用 Collections.sort 方法,将约会的 ArrayList 和我创建的 AppointmentComparator 传递给它。编译时出现“没有合适的排序方法”。这是编译器生成的完整错误消息的链接: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>

变量 book 是一个约会的 ArrayList。 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;
}

}

}

回答by Affe

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.

它需要有实现部分,而不仅仅是包含方法。

回答by nyuen

You need to cast your new AppointmentComparator

您需要投射新的 AppointmentComparator

Collections.sort(book, new (Comparator)AppointmentComparator());

回答by Johnn55

Also we can use inner class for some cases:

我们也可以在某些情况下使用内部类:

public int indexOfLargest(ArrayList<QuakeEntry> Data) {
    Comparator<QuakeEntry> cmtr = new Comparator<QuakeEntry>() {
        @Override
        public int compare(QuakeEntry t, QuakeEntry t1) {
            if (t.getMagnitude() < t1.getMagnitude())
                return -1;
            if (t.getMagnitude() == t1.getMagnitude()) 
                return 1;
            if (t1.getMagnitude() > t1.getMagnitude())
                return 0;
        return 1;
        }
    };

    QuakeEntry max = Collections.max(Data, cmtr);
    int maxIndex = Data.indexOf(max);
    //----------------------------------------------------------------------
    System.out.println("//---------------------------------------------------");
    System.out.println("ArrayList sorted by Magnitude using inner class with Comparator");
    System.out.println("//---------------------------------------------------");
    Collections.sort(Data, cmtr);
    for (QuakeEntry qe : Data) {
        System.out.println(qe);
    }


    return maxIndex;
}

code for all classes: https://github.com/Evegen55/Java_DukeEdu_Coursera_2/blob/master/Earthquakes_Programming%20and%20Interfaces/src/earthquakes_programming_and_interfaces/QuakeEntry.java

所有课程的代码:https: //github.com/Evegen55/Java_DukeEdu_Coursera_2/blob/master/Earthquakes_Programming%20and%20Interfaces/src/earthquakes_programming_and_interfaces/QuakeEntry.java

回答by Akash Yadav

Seems you have not implemented The comparator interface for your AppointmentComparator

似乎您还没有为您的 AppointmentComparator 实现比较器接口