队列:先进先出的线性表,元素间具有一对一的关系。
本程序实现泛型队列。
package pack2;
import java.util.ArrayList;
public class GenericQueue<T> {
private ArrayList<T> list;
public GenericQueue() {
super();
list = new ArrayList<>();
}
public GenericQueue(int capacity) {
super();
try { //如果capacity小于0,抛出并捕获异常(抛出来自new ArrayList<>(capacity))
list = new ArrayList<>(capacity);
}catch(IllegalArgumentException ex) {
System.out.println(ex.getMessage());
System.exit(1);
}
}
public void push(T o) {
list.add(o);
}
public T pop() {
if(isEmpty()) {
System.out.println("This is an empty queue, so cannot pop");
System.exit(1);
}
T temp = list.remove(0);
return temp;
}
public T peak() {
if(isEmpty()) {
System.out.println("This is an empty queue, so cannot peak");
System.exit(2);
}
return list.get(0);
}
public int getSize() {
list.trimToSize(); //调用trimToSize()方法压缩大小为实际大小
return list.size();
}
public String getQueue() {
return "Queue: "+list.toString();
}
public boolean isEmpty() {
return getSize() == 0;
}
}
测试程序如下:
package pack2;
public class TestGeneric {
public static void main(String[] args) {
GenericQueue<String> queue1 = new GenericQueue<>();
queue1.push("China");
queue1.push("is");
queue1.push("a");
queue1.push("country");
System.out.println(queue1.getQueue());
System.out.println("The peek of queue1 is "+queue1.peek());
queue1.pop();
System.out.println("The new peek of queue1 is "+queue1.peek());
System.out.println("The value of popping is "+queue1.pop());
System.out.println(queue1.getQueue());
System.out.println("The current size of the queue1 is "+queue1.getSize());
GenericQueue<Integer> queue2 = new GenericQueue<>();
queue2.push(1);
queue2.push(2);
queue2.push(3);
queue2.push(4);
queue2.push(5);
System.out.println(queue2.getQueue());
}
}