PriorityQueue:
是一个无界的优先级队列,优先级由元素指定(实现Comparable接口)
或者由其构造函数指定一个Comparator。
通过poll或者peak获取优先级最高的元素.
演示代码:
package com.abc.test;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.PriorityQueue;
/**
* 注意:以下测试用例只能单独执行.
*/
public class PriorityQueueTest {
public static class MyElement implements Comparable {
final int order;
final String name;
public MyElement(String name, int order) {
this.name = name;
this.order = order;
}
@Override
public int compareTo(Object o) {
return this.order - ((MyElement) o).order;
}
}
PriorityQueue<MyElement> priorityQueue = new PriorityQueue<>();
/**
* 先准备3个元素,供每个测试用例使用.
*/
@Before
public void init() {
priorityQueue.add(new MyElement("5", 5));
priorityQueue.add(new MyElement("3", 3));
priorityQueue.add(new MyElement("1", 1));
priorityQueue.add(new MyElement("10", 10));
}
/**
* Peek
* 元素1最小.
* size仍然是4.
*/
@Test
public void testPeek() {
MyElement element = priorityQueue.peek();
Assert.assertEquals(element.order, 1);
Assert.assertEquals(priorityQueue.size(), 4);
}
/**
* poll
* 元素1 最小.
* 最后还有3个元素.
*/
@Test
public void testPoll() {
MyElement element = priorityQueue.poll();
Assert.assertEquals(element.order, 1);
Assert.assertEquals(priorityQueue.size(), 3);
}
/**
* clear
*/
@Test
public void testClear() {
priorityQueue.clear();
Assert.assertEquals(priorityQueue.size(), 0);
}
}