我在使用迭代器时遇到问题。我正在编写一个自定义链接列表,就像使用迭代器一样能够遍历该列表。
迭代器如下所示:
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);
}
}
当我尝试在只有一个Node的情况下使用迭代器时,它什么也没做。没有错误或任何东西。但是,如果我有多个节点,则此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;
}
}
我觉得那是超级垃圾,但确实有效。似乎Java先调用
hasNext()
,再调用下一个,因此我必须区别对待特殊情况。| 123
hasNext() == true
next() == 1
1 | 23
hasNext() == true
next() == 2
12 | 3
其中
|
等于光标。准确吗?有没有更好的方法来解决这个问题? 最佳答案
如果只有一个Node,则它的特殊情况是-> next为null。在循环之前,请尝试打印出第一个节点,我认为您的循环可能正在向前看。
关于java - Java迭代器无法使用单个可迭代对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16095668/