在尝试使用此泛型类的优先级队列时,我应该使用Comparator还是Comparable?

时间:2018-04-01 14:56:48

标签: java comparison priority-queue

当尝试在优先级队列中赋予通用对象优先级时,我可以使用哪些来比较它们?我可以在Comparable接口中定义和使用重写的CompareTo方法,还是从Comparator接口中重写Compare方法?或者我可以使用其中一个?感谢

以下是实例变量,类的构造函数和当前的compareTo方法。

private LocalTime scheduledTime; //the scheduled time of the flight
private Event.EventType eventType; //the event type of the flight (arrival or departure)
private String identifier;  // the identifier of the flight
private LocalTime actualTime; //the actual time the flight uses a runway
private Runway runwayUsed; //the runway the flight used to arrive or depart
private int reserveTime; // time the flight uses to reserve a runway 
private LocalTime runwayAvailableTime;


/**
 * Constructor
 * @param scheduledTime the scheduled time of the flight
 * @param eventType the event of the flight (arrival or departure)
 * @param identifier the identifier of the flight
 */
protected Flight(String scheduledTime, String eventType, String identifier) {


    this.scheduledTime = LocalTime.parse(scheduledTime);
    this.eventType = EventType.valueOf(eventType);
    this.identifier = identifier;
    this.actualTime = null;
    this.runwayUsed = null;

} 

//Here is the compareTo method I am currently using. Should I use compare //from the Comparator interface instead?
@Override
public int compareTo(Event otherFlight) {

    Event tmpFlight = (Event) otherFlight;


        if(this.scheduledTime.compareTo(tempFlight.getScheduledTime()) == 0) {
        if(this.eventType.compareTo(tempFlight.getEvent()) == 0){
            return 0;
        } 
        else if(this.eventType.compareTo(tempFlight.getEvent()) > 0){
            return 1;
        } 
        else {
            return -1;
        } 
    } 
    else if(this.scheduledTime.compareTo(tempFlight.getScheduledTime()) < 0) {
        return -1;
    } 
    else {
        return 1;
    }  }

1 个答案:

答案 0 :(得分:1)

由于您已经实施了compareTo,因此您拥有Comparable FlightEvent个实例。

这意味着您已将其设置为与Comparable个对象一起使用。以下所有都应该有效:

Queue<Event> eventQueue = new PriorityQueue<>();
eventQueue.add(new Flight(scheduledTime, eventType, identifier));

或者:

List<Flight> flightList = Arrays.asList(new Flight(scheduledTime, 
                           eventType, identifier));
Queue<Flight> flightQueue = new PriorityQueue<>(flightList);

或者:

List<Event> eventList = ...;
Queue<Event> eventQueue = new PriorityQueue<>(eventList);

PiorityQueue类应该能够根据您的compareTo排序所规定的顺序处理优先级。

注意:如果您的List<Event>包含其他类的实现Event的对象,那么您必须确保其他类也具有compareTo(Event otherFlight)。否则,优先级队列可能会在运行时引发异常。
最好的选择可能是将Flight声明为实现Comparable<Flight>并实例化PriorityQueue<Flight>队列。