首先,是的,这是在学校的作业,但我不是在寻找有人以任何方式重写或彻底检查我的代码.我的问题是:
我被要求编写一个创建扩展Node的队列的类(后者如下所示)
public class Node<T>{
protected T data;
protected Node<T> next;
}
Run Code Online (Sandbox Code Playgroud)
我已经编写了(最可能非常粗略的)方法来执行此操作,以及一个将整数类型存储到队列中的基本测试程序(希望如此).我不知道所有的专业术语,我已经阅读了'generics'文档,但可能已经错过了一个关键点,我已经阅读了链表如何工作(他们的例子在Node类中有更多,这是我' 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;
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
错误是这样的:
incompatible types.
T item = this.base.data;
^
required: T
found: Object
where T is a Type variable: T extends Object declared in class Queue
Run Code Online (Sandbox Code Playgroud)
这里:
public Node base;
public Node end;
Run Code Online (Sandbox Code Playgroud)
应该:
public Node<T> base;
public Node<T> end;
Run Code Online (Sandbox Code Playgroud)
问题是:泛型都是关于编译时的类型检查。当您执行任务时:
T item = this.base.data;
Run Code Online (Sandbox Code Playgroud)
编译器不允许,因为它不进行类型检查。它不会进行类型检查,因为:
public Node base;
Run Code Online (Sandbox Code Playgroud)
相当于:
public Node<Object> base;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1276 次 |
| 最近记录: |