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

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

    Here is one I put together if you have guava. I think it is is pretty complete. Let me know if I missed something.

    You can use the gauva ForwardingBlockingQueue so you don't have to map all the other methods.

    import com.google.common.util.concurrent.ForwardingBlockingQueue;
    
    public class PriorityBlockingQueueDecorator extends
            ForwardingBlockingQueue {
    
        public static final class QueueFullException extends IllegalStateException {
    
            private static final long serialVersionUID = -9218216017510478441L;
    
        }
    
        private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
        private int maxSize;
    
        private PriorityBlockingQueue delegate;
    
        public PriorityBlockingQueueDecorator(PriorityBlockingQueue delegate) {
            this(MAX_ARRAY_SIZE, delegate);
        }
    
        public PriorityBlockingQueueDecorator(int maxSize,
                PriorityBlockingQueue delegate) {
            this.maxSize = maxSize;
            this.delegate = delegate;
        }
    
        @Override
        protected BlockingQueue delegate() {
            return delegate;
        }
    
        @Override
        public boolean add(E element) {
            return offer(element);
        }
    
        @Override
        public boolean addAll(Collection collection) {
            boolean modified = false;
            for (E e : collection)
                if (add(e))
                    modified = true;
            return modified;
        }
    
        @Override
        public boolean offer(E e, long timeout, TimeUnit unit)
                throws InterruptedException {
            return offer(e);
        }
    
        @Override
        public boolean offer(E o) {
            if (maxSize > size()) {
                throw new QueueFullException();
            }
            return super.offer(o);
        }
    }
    

提交回复
热议问题