优先级根据Java中另一个列表的值对pop元素进行排队

时间:2017-05-25 18:08:43

标签: java

我正在从Python过渡到Java,仍然在熟悉Java语法。我正在研究优先级队列(在Python heapq中比喻)并且不确定某些实现,似乎我需要制作一个比较器才能使用它。

假设我有一个队列

Queue<Object> buffer;

// for example, pop buffer element according to `element.value`
// this is not the accurate code but helps illustrate my points
BufferElement0.value() // return 5
BufferElement1.value() // return 3
BufferElement2.value() // return 7

我想要什么

buffer.poll() // return buffer element 2
buffer.poll() // return buffer element 0
buffer.poll() // return buffer element 1

即,一系列值(int)附加到每个缓冲区元素。我怎么能根据这些给定的值弹出缓冲区元素?

更新

对象不是必需的数字,假设对象是

public class Message {

    public final double timeStamp;
    public final String text;
    public final Topic topic;
    public final Status status;
    public final int value;

    public Message(double timeStamp, String text, Topic topic, Status status, int value) {
        this.timeStamp = timeStamp;
        this.text = text;
        this.topic = topic;
        this.status = status;
        this.value = value;
    }


Queue<Message> msgs;
message = msgs.poll()

我们可以根据messsage的{​​{1}}点击value吗?

1 个答案:

答案 0 :(得分:1)

好的,所以你想要按值自动排序。

@Test
public void thing() throws Exception {
    Queue<Integer> queue = new PriorityQueue<>();
    queue.add(5);
    queue.add(3);
    queue.add(7);

    for(Integer thing = queue.poll(); thing != null; thing = queue.poll()) {
        System.out.println(thing);

    }
}

输出:

3
5
7

这适用于可自然排序的事物(AKA:实现Comparable<?>接口)。但是,即使它们没有,您也可以定义自己的比较器并将其提供给构造函数。或者,如果它是您自己的对象之一,则可以在其上实现Comparable<T>。在您的情况下,您使用的数字可以自然排序。