[b][size=medium]Queue interface[/size][/b]
一个队列的接口定义:
队列的每一个方法都有两种形式,一种当操作失败时会抛出异常,另一种失败时会返回特定的值,返回值的类型依赖于具体方法的定义。
[table]
||Throws Exception|Returns special value|
|Insert|add(e)|offer(e)|
|Remove|remove()|poll()|
|Examine|element()|peek()|
[/table]
Queue允许对其可容纳元素的数量加以限制,这样的queue我们称之为bounded(有界的),java.util.concurrent中的queue实现是有界的,java.util中的实现则不是。
下面的例子将展示一个倒数计时器,其参数是倒数的时间值:
接下来这个例子,我们将使用PriorityQueue类,一个Priority queue是一个优先级队列,默认情况下将按照元素的增序排列。我们将使用这个队列还模拟堆排序(构造 PriorityQueue时应该使用了堆排序算法):
(to be continued...)
一个队列的接口定义:
public interface Queue<E> extends Collection<E> {
E element();
boolean offer(E e);
E peek();
E poll();
E remove();
}
队列的每一个方法都有两种形式,一种当操作失败时会抛出异常,另一种失败时会返回特定的值,返回值的类型依赖于具体方法的定义。
[table]
||Throws Exception|Returns special value|
|Insert|add(e)|offer(e)|
|Remove|remove()|poll()|
|Examine|element()|peek()|
[/table]
Queue允许对其可容纳元素的数量加以限制,这样的queue我们称之为bounded(有界的),java.util.concurrent中的queue实现是有界的,java.util中的实现则不是。
下面的例子将展示一个倒数计时器,其参数是倒数的时间值:
import java.util.*;
public class Countdown {
public static void main(String[] args)
throws InterruptedException {
int time = Integer.parseInt(args[0]);
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = time; i >= 0; i--)
queue.add(i);
while (!queue.isEmpty()) {
System.out.println(queue.remove());
Thread.sleep(1000);
}
}
}
接下来这个例子,我们将使用PriorityQueue类,一个Priority queue是一个优先级队列,默认情况下将按照元素的增序排列。我们将使用这个队列还模拟堆排序(构造 PriorityQueue时应该使用了堆排序算法):
static <E> List<E> heapSort(Collection<E> c) {
Queue<E> queue = new PriorityQueue<E>(c);
List<E> result = new ArrayList<E>();
while (!queue.isEmpty())
result.add(queue.remove());
return result;
}
(to be continued...)