如何使用 compareTo 方法将值插入 java 中的队列?

How do I use the compareTo method to insert values into a queue in java?

我正在尝试将排序后的值插入到 Java 中的队列中。我创建了一个 compareTo 方法,需要帮助将其添加到队列中。 compareTo 方法在一个 class 中,队列在另一个 class.

比较方法:

public int compareTo(Event cmp) {
        if(getArrTime() > cmp.arrTime) {
            return 1;
        }
        else if(getArrTime() < cmp.arrTime) {
            return -1;
        }
        else {
            return 0;
        }
    }

这就是我要为插入方法做的事情:

public void enque(Object insertSort) {
        //if compareTo is greater than param, append to the front
        //if equal, use event type. If it's 'A' append before 'D'
        //if compareTo is less than the param, add to end
        //return list
    }

您使用的 Queue 是什么意思?你看过 PriorityQueue 吗?这是一个使用比较器的排序队列。

查看此问题的答案:Sorted collection in Java

这是一个使用问题中的事件并按事件类型 属性 字母顺序排序的工作示例:

PriorityQueue<Event> queue = new PriorityQueue<>(
    new Comparator<Event>() {

        @Override
        public int compare(Event o1, Event o2) {
            int result = o1.getEventType()
                .compareTo(o2.getEventType()); 
            return result;
        }
                
});

queue.add(new Event("C"));
queue.add(new Event("A"));
queue.add(new Event("B"));    
    
while(!queue.isEmpty()) {
    System.out.println(queue.poll().getEventType());
}

打印: 一种 乙 C