【问题标题】:Queue operations in Java [closed]Java中的队列操作[关闭]
【发布时间】:2013-03-02 20:05:56
【问题描述】:

我有一个任务要做,涉及在队列上创建和执行操作... 在指令中,他开始这样说......

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

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

提前致谢!

【问题讨论】:

标签: java oop generics queue


【解决方案1】:

Node&lt;T&gt; 允许您将队列的所有节点设为相同类型,并在编译时指定该类型。

例如,您可以有以下类型的节点:

  • int
  • 字符串
  • YourDefinedJobType

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

通用表示法要求只有该类型的节点才能排队,这非常方便,因为如果您设置 Node&lt;String&gt; 并尝试添加 YourDefinedJobType 的节点,则会引发运行时错误。

其次,当您让Node&lt;String&gt; 工作时,您将让Node&lt;YourDefinedJobType&gt; 工作而无需任何额外的队列代码。

此外,您可以保证拥有正确类型的节点,并且不必强制转换它们。

Joshua Bloch 的书Effective Java 中有一个示例章节涉及泛型。它当然值得一读,并会回答您关于泛型的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多