Is there a PriorityQueue implementation with fixed capacity and custom comparator?

后端 未结 9 2455
后悔当初
后悔当初 2020-11-28 05:59

Related questions:

  • Java PriorityQueue with fixed size
  • How do I use a PriorityQueue?
  • get indexes of n smallest elements in an array
相关标签:
9条回答
  • 2020-11-28 06:52

    Exactly what I was looking for. However, the implementation contains a bug:

    Namely: if elementsLeft > 0 and e is already contained in the TreeSet. In this case, elementsLeft is decreased, but the number of elements in the TreeSet stays the same.

    I would suggest to replace the corresponding lines in the add() method by

            } else if (elementsLeft > 0) {
            // queue isn't full => add element and decrement elementsLeft
            boolean added = super.add(e);
            if (added) {
                elementsLeft--;
            }
            return added;
    
    0 讨论(0)
  • 2020-11-28 06:52

    Try this code:

    public class BoundedPQueue<E extends Comparable<E>> {
    /**
     * Lock used for all public operations
     */
    private final ReentrantLock lock;
    
    PriorityBlockingQueue<E> queue ;
    int size = 0;
    
    public BoundedPQueue(int capacity){
        queue = new PriorityBlockingQueue<E>(capacity, new CustomComparator<E>());
        size = capacity;
        this.lock = new ReentrantLock();
    
    }
    
    public boolean offer(E e) {
    
    
        final ReentrantLock lock = this.lock;
        lock.lock();
        E vl = null;
        if(queue.size()>= size)  {
            vl= queue.poll();
            if(vl.compareTo(e)<0)
                e=vl;
        }
    
        try {
            return queue.offer(e);
        } finally {
            lock.unlock();
        }
    
    
    }
    
    public E poll()  {
    
        return queue.poll();
    }
    
    public static class CustomComparator<E extends Comparable<E>> implements Comparator<E> {
    
    
        @Override
        public int compare(E o1, E o2) {
            //give me a max heap
             return o1.compareTo(o2) *-1;
    
        }
    }
    
    }
    
    0 讨论(0)
  • 2020-11-28 06:53

    Though an old question but it may be helpful to somebody else. You can use minMaxPriorityQueue of Google's Java library guava.

    0 讨论(0)
提交回复
热议问题