繁体   English   中英

如何使用 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 吗? 这是一个使用比较器的排序队列。

请参阅此问题的答案: Java 中的排序集合

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

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());
}

打印:AB C

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM