三、 测试Queue类
下列类用于测试"泛型"队列。
package com.heatonresearch.examples.collections;
public class TestQueue {
public static void main(String args[]) {
Queue<Integer> queue = new Queue<Integer>();
queue.push(1);
queue.push(2);
queue.push(3);
try {
System.out.println("Pop 1:" + queue.pop());
System.out.println("Pop 2:" + queue.pop());
System.out.println("Pop 3:" + queue.pop());
}
catch (QueueException e) { e.printStackTrace(); }
}
}
前面的代码中创建的队列仅接收整型对象。
Queue<Integer> queue = new Queue<Integer>();
接下来的测试把三个整数添加到该队列上。
queue.push(1);
queue.push(2);
queue.push(3);
注意,添加到该队列中的这些数字都是原始的类型。因为J2SE的自动装箱特性,这些原始的int类型被自动地转变成Integer对象。
接下来,该测试使用pop方法检索对象。在该队列为空的情况下,该测试捕获到QueueException异常。从队列中弹出三个数字的结果是:
1
2
3
尽管在这里作为一接收的整数队列显示,但是因为泛型,所以队列类对于任何Java对象情况都能正常工作。
