我遇到了迭代器的问题。我正在编写一个自定义链表,因为它使用迭代器来遍历列表。
迭代器如下所示:
public class NodeIterator implements Iterator<Node> {
private Node current = head;
private Node lastReturned = head;
public boolean hasNext() {
return lastReturned.getLink() != null;
}
public Node next() {
lastReturned = current;
current = current.getLink();
return lastReturned;
}
public void remove() {
removeNode(lastReturned);
lastReturned = null;
}
}
我仍处于早期阶段,因此我正在通过使用此方法填充节点来从控制台测试数据结构。
private static void MethodToPopulateNodes() {
MyObject o = new MyObject();
String[] responses = new String[prompts.length];
scanner = new Scanner(System.in);
boolean done = false;
String s = null;
while (!done) {
int i = 0;
for (String prompt : prompts) {
System.out.println(prompt);
s = scanner.nextLine();
if (s.equalsIgnoreCase("stop")) {
done = true;
break;
} else {
responses[i] = s;
}
i++;
}
if (done) {
break;
}
o = new MyObject(responses);
myNode.add(c);
}
}
当我在只有一个节点时尝试使用迭代器时,它什么也没做。没有错误或任何东西。但是,如果我有多个节点,则此 foreach 可以完美运行。
public static void main(String[] args) {
myNode = new Node();
methodToPopulateLinkedList();
for (Node node : myNode) {
//toString is overridden for my object
System.out.println(node.getData().toString());
}
}
更新:我编辑了迭代器以hasNext() == true
在第一次迭代时返回:
public class NodeIterator implements Iterator<Node> {
private boolean done = false;
private Node current = head;
private Node lastReturned = head;
public boolean hasNext() {
if (head == tail && head != null && !done) {
done = true;
return true;
}
return lastReturned.getLink() != null;
}
public Node next() {
lastReturned = current;
current = current.getLink();
return lastReturned;
}
public void remove() {
removeNode(lastReturned);
lastReturned = null;
}
}
我觉得那是超级笨拙的,但它有效。似乎 JavahasNext()
在调用 next 之前先调用,所以我必须以不同的方式处理特殊情况。
|123
hasNext() == true
next() == 1
1|23
hasNext() == true
next() == 2
12|3
where|
等于光标。那准确吗?有没有更好的方法来解决这个问题?