代码之家  ›  专栏  ›  技术社区  ›  LuminousNutria

在Java中实现队列,但不能重写迭代器()方法

  •  0
  • LuminousNutria  · 技术社区  · 6 年前

    我试图通过在我自己的“MyQueue”类中实现队列接口来发展我对该接口的了解。但是,我想重写迭代器()方法。因为我不能同时实现迭代器和队列接口,所以我不知所措。

    cannot convert from MyQueue<E>.QueueIterator to Iterator<E> 当我将鼠标移到单词下面的红色下划线上时 new QueueIterator()

    另外,当我尝试实现我的“QueueIterator”内部类时,Eclipse给了我一个错误, syntax error on token "class", @ expected 当我将鼠标移到单词下面的红色下划线上时 class

    在下面的代码示例中,我删除了所有与我的问题无关的方法。我知道我必须实现这些方法来实现队列。我只是想把问题弄清楚。

    MyQueue类:

    import java.util.Collection;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    import java.util.Queue;
    
    /**
     * A custom queue class. Uses a singly-linked list.
     */
    public class MyQueue<E> implements Queue {
       // the top of the queue
       private Node<E> first;
       private int size;
    
       /**
        * Creates new myQueue object
        */
       public MyQueue() {
          first = null;
          current = null;
          size = 0;
       }
    
       @Override
       public Iterator<E> iterator() {
          return new QueueIterator();
       }
    
      /**
       * Holds Objects and points to the next one.
       *
       */
      private class Node<E> {
         private E data;
         private Node<E> next;
    
         /**
          * Creates a Node object
          * @param data The Object to be held by the Node
          */
         Node(E data) {
            this.data = data;
            this.next = null;
         }
    
         private Node<E> getNext() {
            return this.next;
         }
    
         private E getData() {
            return this.data;
         }
      }
    
      /**
       * Iterator implementation
       */
      private class QueueIterator() {
    
         private Node<E> curNode;
    
         public QueueIterator() {
            curNode = null;
         }
    
         public boolean hasNext() {
            if(curNode == null && first != null) {
               return true;
            } else if (curNode.getNext() != null) {
               return true;
            } else {
               return false;
            }
         }
    
         public E next() {
            if(curNode == null && first != null) {
               curNode = first;
               return curNode.getData();
            }
    
            if(!hasNext()) {
               throw new NoSuchElementException();
            }
    
            curNode = curNode.getNext();
            return curNode.getData();
         }
      }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Bernie    6 年前

    QueueIterator 需要实施 Iterator<E> .

    您不应该在这一行有括号:

      private class QueueIterator() {
    

    应该是:

      private class QueueIterator {
    

      private class QueueIterator implements Iterator<E> {