队列是遵循先进先出(First-In-First-Out)模式的线性表。
一般有以下操作:
boolean add(E e);
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
boolean offer(E e);
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
E remove();
Retrieves and removes the head of this queue. @throws NoSuchElementException if this queue is empty
E poll();
Retrieves and removes the head of this queue, or returns null if this queue is empty.
E element();
Retrieves, but does not remove, the head of this queue. @throws NoSuchElementException if this queue is empty
E peek();
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
由于队列对数据的get/set特殊,一般采用链接实现起来比较方便。参照链表就可以实现,这里就不给出具体的代码了。
public class LinkedQueue<E> implements Queue<E> {
}
优先队列是基于优先级处理对象进出操作。优先队列要求使用Comparable和Comparator接口给对象排序,并且在排序时会按照优先级处理其中的元素。PriorityQueue是非线程安全的, PriorityBlockingQueue(实现BlockingQueue接口)用于Java多线程环境。
方法iterator()中提供的迭代器并不保证以有序的方式遍历优先级队列中的元素。
可以在构造函数中指定如何排序。
此实现为插入方法(offer、poll、remove() 和 add 方法)提供 O(log(n)) 时间;
为 remove(Object) 和 contains(Object) 方法提供线性时间;
为检索方法(peek、element 和 size)提供固定时间。
实例
后半部分模拟乘坐高铁的检票到乘坐环节(假设全车座位序号为连续数字)。
public class PriorityQueueModel {
private int id;
private String name;
getter/setter(略)
}
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
public class PriorityQueueExample {
// Comparator
public static Comparator<PriorityQueueModel> idComparator = new Comparator<PriorityQueueModel>() {
@Override
public int compare(PriorityQueueModel c1, PriorityQueueModel c2) {
return (int) (c1.getId() - c2.getId());
}
};
public static void main(String[] args) {
// 优先队列示例
Queue<Integer> seqPriorityQueue = new PriorityQueue<>(7);
Random rand = new Random();
for(int i = 0; i < 7; i++) {
seqPriorityQueue.add(new Integer(rand.nextInt(100)));
}
seqPriorityQueue.add(new Integer(0));
seqPriorityQueue.add(new Integer(-1));
int size = seqPriorityQueue.size(); // note : here
for(int i = 0; i < size; i ++) {
Integer in = seqPriorityQueue.poll(); // poll
System.out.println("SEQ:" + in);
}
System.out.println("size=" + seqPriorityQueue.size() + "\n");
// 优先队列使用示例
Queue<PriorityQueueModel> 动车1号 = new PriorityQueue<>(10, idComparator);
Random 检票机 = new Random();
for(int i = 0; i < 7; i++) {
int id = 检票机.nextInt(100000);
动车1号.add(new PriorityQueueModel(id, "座号" + id));
}
System.out.println("\n乘车信息:");
while(true){
PriorityQueueModel model = 动车1号.poll(); // poll
if(model == null) {
break;
}
System.out.println(model.getName());
}
}
}
输出结果:
SEQ:-1
SEQ:0
SEQ:4
SEQ:37
SEQ:58
SEQ:79
SEQ:84
SEQ:90
SEQ:90
size=0
创建 座号1256
创建 座号39916
创建 座号11350
创建 座号10287
创建 座号79812
创建 座号44573
创建 座号15600
乘车信息:
座号1256
座号10287
座号11350
座号15600
座号39916
座号44573
座号79812