【发布时间】:2016-04-09 23:25:10
【问题描述】:
您好,我正在尝试创建一个队列,该队列将重构我的代码以删除 Eclipse 错误消息:“GGCQueue 是原始类型。对泛型类型 GGCQueue 的引用应该被参数化”。我想创建一个永远不会包含超过 10 个元素的队列。我正在尝试遵循“通用”原则来做到这一点,但目前我无法弄清楚如何做到这一点。我有以下代码(在 GGCQueue 类中,构造函数 GGCQueue() 是我需要实现的地方):
import java.util.LinkedList;
import java.util.List;
public class GenericsProblem {
public static void main(String[] args) {
GGCQueue ggcQ = new GGCQueue();
ggcQ.offer(100);
ggcQ.offer(1000);
ggcQ.offer(3.33D);
ggcQ.offer(9);
ggcQ.offer(7);
ggcQ.offer(9.001F);
System.out.println("polling the queue, expecting 100, got:" + ggcQ.poll());
System.out.println("polling the queue, expecting 1000, got:" + ggcQ.poll());
System.out.println("polling the queue, expecting 3.33, got:" + ggcQ.poll());
System.out.println("polling the queue, expecting 9, got:" + ggcQ.poll());
System.out.println("polling the queue, expecting 7, got:" + ggcQ.poll());
System.out.println("polling the queue, expecting 9.001, got:" + ggcQ.poll());
}
}
class GGCQueue<E> {
List<E> q = new LinkedList<E>();
public GGCQueue() {
//TODO MAKE THE SMALL QUEUE <= 10 ELEMENTS
}
public void offer(E element) {
if (q.size() == 10)
return;
q.add(element);
}
public E poll() {
E element = q.remove(0);
return element;
}
}
【问题讨论】:
-
澄清一点,当我运行它时,我希望将结果发送到 SOP(轮询队列,期望 100,得到:100...等等)。感谢您的帮助!
标签: java list generics linked-list queue