2015-09-28 4 views
-1

У меня есть задача кодировать класс ниже ... У меня проблема в методе итератора() У меня в нем много ошибок, я не знаю, как это сделать, чтобы исправить это .. Можете ли вы предложить способ исправить код в методе итератора() ... Вы также можете увидеть другие части класса ... Я помещаю комментарии из затмения рядом с каждой зараженной линией. спасибоКак использовать итератор в реализованной очереди

package queue; 
import java.util.*; 

public class FifoQueue<E> extends AbstractQueue<E> implements Queue<E> { 
    private QueueNode<E> last; 
    private int size; 

    public FifoQueue() { 

    } 

    /** 
    * Returns an iterator over the elements in this queue 
    * @return an iterator over the elements in this queue 
    */ 
    public Iterator<E> iterator() { 
     QueueNode<E> position =last; 
     Iterator itr = position.iterator(); // The method iterator() is //undefined for the type FifoQueue.QueueNode<E>- Iterator is a raw type. References //to generic type Iterator<E> should be 
    parameterized 
     while(itr.hasNext){ // hasNext cannot be resolved or is not a field 
      int object=itr.next(); //Type mismatch: cannot convert from Object to int 
     return object; //Type mismatch: cannot convert from int to Iterator<E> 

      } 
     } 

    /** 
    * Returns the number of elements in this queue 
    * @return the number of elements in this queue 
    */ 
    public int size() {  
     return size; 
    } 

    /** 
    * Inserts the specified element into this queue, if possible 
    * post: The specified element is added to the rear of this queue 
    * @param x the element to insert 
    * @return true if it was possible to add the element 
    *   to this queue, else false 
    */ 
    public boolean offer(E x) { 
     QueueNode<E> q = new QueueNode<E>(x); 
     if(last!=null){ 
     q.next=last.next; 
     last.next=q; 
     return true; 

     } else { 
     return true; 
    } 
    } 

    /** 
    * Retrieves and removes the head of this queue, 
    * or null if this queue is empty. 
    * post: the head of the queue is removed if it was not empty 
    * @return the head of this queue, or null if the queue is empty 
    */ 
    public E poll() { 
     if(last==null){ 
      return null; 
     } 
      QueueNode<E> n=last.next; 
      last.next=last.next.next; 
      size=size-1; 
      return n.element; 

     } 


    /** 
    * Retrieves, but does not remove, the head of this queue, 
    * returning null if this queue is empty 
    * @return the head element of this queue, or null 
    *   if this queue is empty 
    */ 
    public E peek() { 
     if(last==null){ 
      return null; 
     } 
     QueueNode<E> n=last; 
     while(n.next !=null){ 

     } 
     return n.element; 
    } 


    private static class QueueNode<E> { 
     E element; 
     QueueNode<E> next; 

     private QueueNode(E x) { 
      element = x; 
      next = null; 
     } 

    } 

} 
+0

Вы не можете назвать '.iterator()' на что-либо; ваш 'QueueNode' не имеет реализации' iterator() '. Вам нужно написать класс, который реализует «Итератор» и заполнить методы 'hasNext()', 'next()' и 'remove()'. –

+0

Что такое 'QueueNode' – Vaseph

+0

Vaseph 2' QueueNode', это должна быть очередь одного элемента – java

ответ

0

Ваш метод iterator() должен вернуть реализацию интерфейса Iterator<E>. Вероятно, вы захотите сделать это как частный внутренний класс, чтобы он имел доступ к полям очереди.

Класс итератора должен сохранять текущую позицию и проходить через ваши узлы по звонкам до next().

Возможно, вы захотите реализовать отказоустойчивую логику, чтобы предотвратить проблемы с обновлением очереди во время итерации. Добавьте счетчик изменений в очередь и добавьте изменения (вставить/удалить). Помните счетчик изменений в момент создания итератора, и если он отличается при вызове next(), бросьте ConcurrentModificationException.

Это скелет, чтобы вы начали:

public Iterator<E> iterator() { 
    return new FifoIterator(); 
} 

private final class FifoIterator implements Iterator<E> { 
    private QueueNode<E> curr; 
    FifoIterator() { 
     this.curr = FifoQueue.this.last; 
    } 
    @Override 
    public boolean hasNext() { 
     return (this.curr != null); 
    } 
    @Override 
    public E next() { 
     if (this.curr == null) 
      throw new NoSuchElementException(); 
     this.curr = this.curr.next; 
     E e = this.curr.element; 
     if (this.curr == FifoQueue.this.last) 
      this.curr = null; 
     return e; 
    } 
} 
+0

В чем смысл @Override и почему вы выполняете несколько подклассов в своем коде и что это значит 'if (this.curr == FifoQueue.this.last)' почему вы написали 'FifoQueue' спасибо – java

+0

См. Javadoc of [@ Переопределение] (https://docs.oracle.com/javase/7/docs/api/java/lang/Override.html). --- Не знаю, что вы подразумеваете под «несколькими подклассами». Существует 1 внутренний класс, реализующий интерфейс. Нет подклассов. --- Учитывая вашу реализацию 'poll()', ваши узлы находятся в круговой цепочке «последующих» ссылок, поэтому, если вы продолжаете продвигать итератор, перейдя в 'next', когда вы остановитесь? Ответ: Когда вы вернетесь туда, где вы начали. – Andreas

Смежные вопросы