Created
March 4, 2015 14:19
-
-
Save eleco/ea583990bb2ff3fdebdb to your computer and use it in GitHub Desktop.
Bounded priority queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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