删除优先级队列的尾部元素

P R*_*P R 7 java priority-queue

如何删除优先级队列的尾部元素?我正在尝试使用优先级队列实现波束搜索,一旦优先级队列已满,我想删除最后一个元素(具有最低优先级的元素).

谢谢!

use*_*353 5

没有简单的方法.将元素从原始复制到新的除了最后一个.

PriorityQueue removelast(PriorityQueue pq)
{

    PriorityQueue pqnew;

    while(pq.size() > 1)
    {
        pqnew.add(pq.poll());
    }

    pq.clear();
    return pqnew;
}
Run Code Online (Sandbox Code Playgroud)

叫做

pq = removelast(pq);
Run Code Online (Sandbox Code Playgroud)


mat*_*tts 5

您可以使用Guava的MinMaxPriorityQueue来执行此操作.它为队列的两端提供了peek,poll和remove方法.

另一种选择是编写一个强制边界的Queue包装器,类似于这个答案.你需要执行offer,addaddAll检查能力.就像是:

public class BoundedQueue<E> implements Serializable, Iterable<E>, Collection<E>, Queue<E> {
    private final Queue<E> queue;
    private int capacity;

    public BoundedQueue(Queue<E> queue, int capacity) {
        this.queue = queue;
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E o) {
        if (queue.size() >= capacity)
            return false;
        return queue.add(o);
    }

    @Override
    public boolean add(E o) throws IllegalStateException {
        if (queue.size() >= capacity)
            throw new IllegalStateException("Queue full"); // same behavior as java.util.ArrayBlockingQueue
        return queue.add(o);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean changed = false;
        for (E o: c)
            changed |= add(o);
        return changed;
    }

    // All other methods simply delegate to 'queue'
}
Run Code Online (Sandbox Code Playgroud)


use*_*421 5

使用反相比较器并从头上取下。如果您同时需要头部和尾部,那么您使用的是错误的数据结构。