package com.heatonresearch.examples.collections; import java.util.*; public class Queue { private ArrayList list = new ArrayList(); public void push(T obj) { list.add(obj); } public T pop() throws QueueException { if (size() == 0) throw new QueueException( "Tried to pop something from the queue, " + "when it was empty"); T result = list.get(0); list.remove(0); return result; } public boolean isEmpty() { return list.isEmpty(); } public int size() { return list.size(); } public void clear() { list.clear(); } } 前面的代码声明了队列类,这样它可以接收一个泛型类型。
public class Queue 泛型类型"T"是该类类型-它将被放入到该队列中去。为了把这些项存储到一个队列中,该类还要创建一个接收"T"类型的ArrayList。 push方法很简单的。它接收单一的类型为泛型"T"的对象,并且把它添加到ArrayList上。
package com.heatonresearch.examples.collections; public class QueueException extends Exception { public QueueException(String msg) { super(msg); } } 下面是抛出QueueException类型异常的代码:
if (size() == 0) throw new QueueException("Tried to pop something from the queue, " + "when it was empty"); 如果队列不空,该方法将从队列中检索最后一个元素,在一个名叫result的变量中存储它,然后从该列表中删除这个项。下面几行代码实现了这一功能:
T result = list.get(0); list.remove(0); return result; 注意,该临时变量也是泛型类型"T"。当这个类与真实的代表泛型类型的Java类型一起使用时,为了实现最大程度上的兼容性,无论你何时存取这些变量,确保总是使用泛型类型是非常重要的。