【发布时间】:2018-12-11 22:08:11
【问题描述】:
我正在尝试通过在我自己的“MyQueue”类中实现 Queue 接口来发展我的知识。但是,我想重写 iterator() 方法。由于不能同时实现Iterator和Queue接口,我很茫然。
在我的 iterator() 方法中,当我将鼠标悬停在 new QueueIterator() 下方的红色下划线时,Eclipse 给出了错误 cannot convert from MyQueue<E>.QueueIterator to Iterator<E>。
另外,当我尝试实现我的“QueueIterator”内部类时,当我将鼠标悬停在单词class 下方的红色下划线时,Eclipse 给了我错误syntax error on token "class", @ expected。
在下面的代码示例中,我删除了所有与我的问题无关的方法。我知道我必须实现这些方法来实现队列。我只是想让问题更清楚。
如何重写 iterator() 方法?
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();
}
}
【问题讨论】:
标签: java collections iterator queue singly-linked-list