Skip to content

Instantly share code, notes, and snippets.

@eleco
Created March 4, 2015 14:19
Show Gist options
  • Save eleco/ea583990bb2ff3fdebdb to your computer and use it in GitHub Desktop.
Save eleco/ea583990bb2ff3fdebdb to your computer and use it in GitHub Desktop.
Bounded priority queue
import java.util.PriorityQueue;
public class BoundedPriorityQueue<T> extends PriorityQueue<T> {
final private int maxSize ;
public BoundedPriorityQueue(int maxSize) {
this.maxSize = maxSize;
}
@Override
public boolean add (T t) {
boolean added = offer(t);
if (!added) {
return false;
} else if (size() > maxSize) {
this.remove(this.toArray()[this.size()-1]);
}
return true;
}
}
import org.junit.Test;
import java.util.PriorityQueue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
public class BoundedPriorityQueueTest {
private BoundedPriorityQueue<String> queue= new BoundedPriorityQueue(3);
@Test
public void testBoundedQueue() {
queue.add("B");
queue.add("A");
queue.add("C");
queue.add("D");
assertThat(queue.poll(), is("A"));
assertThat(queue.poll(), is("B"));
assertThat(queue.poll(), is("C"));
assertNull(queue.poll());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment