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

后端 未结 9 2514
后悔当初
后悔当初 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

    Try this code:

    public class BoundedPQueue> {
    /**
     * Lock used for all public operations
     */
    private final ReentrantLock lock;
    
    PriorityBlockingQueue queue ;
    int size = 0;
    
    public BoundedPQueue(int capacity){
        queue = new PriorityBlockingQueue(capacity, new CustomComparator());
        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> implements Comparator {
    
    
        @Override
        public int compare(E o1, E o2) {
            //give me a max heap
             return o1.compareTo(o2) *-1;
    
        }
    }
    
    }
    

提交回复
热议问题