【发布时间】:2015-12-14 18:37:47
【问题描述】:
我在整个迭代器概念上遇到了一些问题,对于我的一个测验中的一个问题,我真的不明白发生了什么。
public static void main(String[] args)
{
Deque<String> SQ1 = new ArrayDeque<String>();
SQ1.add("Give");
SQ1.add("Me");
SQ1.add("The");
SQ1.add("Best");
SQ1.add("Of");
SQ1.add("Both");
SQ1.add("Worlds");
Iterator<String> It = SQ1.iterator();
while(It.hasNext())
{
if(It.next().equals("Give"))
System.out.print(It.next());
}
}
这是代码,问题是输出是什么。正确答案是"Me",我以为是"Give"。我不明白整个过程是如何进行的。
这是我的理解:
它确实有一个next。如果next 等于"Give",它将打印出next 值。在这种情况下,该值应该是“给予”,不是吗?
有人可以帮我理解一下吗?
【问题讨论】:
-
在
if内部,它调用next().equals("Give"),它在迭代到"Give"时捕获它。然后在打印时,它再次调用next(),将其迭代到"Me"。 -
谢谢!这是我的理论之一,但我认为它没有意义。谢谢你帮我解决这个问题。
-
Returns the next element in the iteration.- docs.oracle.com/javase/7/docs/api/java/util/Iterator.html -
此外,在标准 Java 编码约定中,局部变量不以大写字母开头。