我有一项任务要做,涉及在队列上创建和执行操作... 在说明中,他首先这样说......
Node Class: You will extend the following class for (some of) the questions below.
public class Node<T>{
protected T data;
protected Node<T> next;
}
Implement the QUEUE (FIFO) abstract data type. For this, you will create a class called Queue that extends Node<T>. Your class should have the following methods:
public void enqueue(Node<T> item)
// Purpose: adds item to the queue
// Preconditions: item should exists (not be null)
// Postconditions: item is added to the end of the queue
// the size of the queue is increased by 1
...等等,还有几页要求等...
我想知道一些我不明白的事情......
public class Node<T>
是什么意思意思是? (斜体部分)。
此外,除了入队方法之外,还有更多方法,因此我假设正确的设计需要我在该方法之外创建队列?
提前致谢!
最佳答案
Node<T>
允许您使队列的所有节点具有相同类型,并在编译时指定该类型。
例如,您可以拥有以下类型的节点:
- 整数
- 字符串
- 您定义的作业类型
(但只有您指定的单一类型可以进入队列。)
通用表示法要求仅对该类型的节点进行排队,这非常方便,因为如果设置 Node<String>
将引发运行时错误并且您尝试添加 YourDefinedJobType 的节点。
第二,当你得到Node<String>
时工作,你会得到 Node<YourDefinedJobType>
无需任何额外的队列代码即可工作。
此外,保证您拥有正确类型的节点,并且不必强制转换它们。
Joshua Bloch 的书《Effective Java》中有一个示例章节涉及泛型。这当然值得一读,并将回答您有关泛型的问题。
关于java - Java中的队列操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15178866/