您好我正在尝试创建一个队列来重构我的代码以删除Eclipses错误消息:“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;
}
}
答案 0 :(得分:1)
看起来你想要:
GGCQueue<Number> ggcQ = new GGCQueue<>();