Java中的队列操作

时间:2013-03-02 20:05:57

标签: java oop generics queue

我有一项任务涉及在队列上创建和执行操作...... 在说明中,他开始说这个......

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>是什么意思? (斜体部分)。

此外,除了排队之外还有更多方法,所以我假设正确的设计需要我在这个方法之外创建队列?

提前致谢!

1 个答案:

答案 0 :(得分:1)

Node<T>允许您使队列中的所有节点具有相同的类型,并在编译时指定该类型。

例如,您可以拥有类型为

的节点
  • INT
  • 字符串
  • YourDefinedJobType

(但只有您指定的单一类型可以进入队列。)

通用表示法要求只对该类型的节点进行排队,这非常方便,因为如果设置Node<String>并尝试添加YourDefinedJobType节点,则会抛出运行时错误。

其次,当Node<String>工作时,您将Node<YourDefinedJobType>无需任何其他队列代码即可正常工作。

此外,您可以保证拥有正确类型的节点,而不必投射它们。

Joshua Bloch的书“ Effective Java ”中有一个样本章节,涉及泛型。这当然值得一读,并会回答你关于泛型的问题。