All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.browseengine.bobo.util.BoundedPriorityQueue Maven / Gradle / Ivy

package com.browseengine.bobo.util;

import java.util.Comparator;
import java.util.PriorityQueue;

public class BoundedPriorityQueue extends PriorityQueue {
  /**
   *
   */
  private static final long serialVersionUID = 1L;

  private final int _maxSize;

  public BoundedPriorityQueue(int maxSize) {
    super();
    _maxSize = maxSize;
  }

  public BoundedPriorityQueue(Comparator comparator, int maxSize) {
    super(maxSize, comparator);
    _maxSize = maxSize;
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean offer(E o) {
    int size = size();
    if (size < _maxSize) {
      return super.offer(o);
    } else {
      E smallest = super.peek();
      Comparator comparator = super.comparator();
      boolean madeIt = false;
      if (comparator == null) {
        if (((Comparable) smallest).compareTo(o) < 0) {
          madeIt = true;
        }
      } else {
        if (comparator.compare(smallest, o) < 0) {
          madeIt = true;
        }
      }

      if (madeIt) {
        super.poll();
        return super.offer(o);
      } else {
        return false;
      }
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy