首先,是的,这是学校的作业,但我不是在找人以任何方式重写或检修我的代码。我的问题是:
我被要求编写一个类来创建一个扩展 Node 的队列(后者如下所示)
public class Node<T>{
protected T data;
protected Node<T> next;
}
我已经编写了(一个很可能非常粗略的)方法来做到这一点,以及一个将整数类型存储到队列中的基本测试程序(希望如此)。我不知道所有的专业术语,我已经阅读了“泛型”文档,但可能错过了一个关键点,我已经阅读了链表的工作原理(他们的例子在节点类中有很多,这是我的东西) m 不允许在此分配中编辑),以及循环数组等。当我运行我的代码时,我得到了一个我没想到的关于类型的错误。我将发布我的相关代码,有人可以大致解释一下我做了什么来得到这个(而是......在我的代码中我不应该使用的地方?)
public class Queue<T> extends Node<T> {
public Node base;
public Node end;
public void enqueue(T item) {
Node newItem = new Node();
newItem.data = item;
newItem.next = null;
if (isEmpty()) { //Sets to item count of 1
this.base = newItem; //Base becomes the new item
this.base.next = this.end; //Base Points Next as End
this.end.next = this.base; //End points to the one before it (base)
}
else { //Sets to item count above 1.
this.end.next.next = newItem; //The Last Item Now Points Next as the New Item (End is never counted as an item)
this.end.next = newItem; //End now points to the next final item.
}
}
public T dequeue() {
if (isEmpty()) {
return (null);
}
else {
T item = this.base.data;
if (this.base.next == this.end) {
this.base = null;
this.end = null;
}
else {
this.base = this.base.next;
}
return (item);
}
}
public int size() {
int count = 0;
for (Node node = base; node != null; node = node.next) {
count++;
}
return count;
}
public boolean isEmpty() {
return (base == null);
}
public Queue() {
this.base = null;
this.end = null;
}
}
TestQueue.java 代码是:
public class TestQueue {
public static void main(String args[]) {
QueueStuff<Integer> firstQueue = new QueueStuff<>();
firstQueue.enqueue (66);
firstQueue.enqueue (6);
firstQueue.enqueue (666);
firstQueue.enqueue (0);
firstQueue.enqueue (6666);
//firstQueue.printQueue();
}
}
错误是这样的:
incompatible types.
T item = this.base.data;
^
required: T
found: Object
where T is a Type variable: T extends Object declared in class Queue