Java 使用 for 语句和 while 语句向前移动迭代器的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/515562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between moving an Iterator forward with a for statement and a while statement
提问by alepuzio
When I use an Iterator of Object I use a while loop(as written in every book learning Java, as Thinking in Javaof Bruce Eckel):
当我使用对象的迭代器时,我使用了一个while 循环(每本学习 Java 的书中都写过,如Bruce Eckel 的Thinking in Java):
Iterator it=...
while(it.hasNext()){
//...
}
but sometime i saw than instead somebody use the for loop:
但有时我看到有人使用for 循环:
Iterator it=...
for (Iterator it=...; it.hasNext();){
//...
}
I don't' understand this choice:
我不明白这个选择:
- I use the for loopwhen I have a collection with ordinal sequence (as array) or with a special rule for the step (declared generally as a simple increment
counter++
). - I use the while loopwhen the loop finishes with I have'nt this constraints but only a logic condition for exit.
- 当我有一个带有序数序列(作为数组)或具有特殊规则的步骤(通常声明为简单增量)的集合时,我使用for 循环
counter++
。 - 当循环结束时我使用while 循环我没有这个约束,但只有退出的逻辑条件。
It's a question of style-coding without other cause or it exists some other logic (performance, for example) that I don't' know?
这是一个没有其他原因的样式编码问题,或者它存在一些我不知道的其他逻辑(例如性能)?
Thanks for every feedback
感谢您的每一个反馈
采纳答案by David Hanak
The correct syntax for the for loop is:
for 循环的正确语法是:
for (Iterator it = ...; it.hasNext(); ){
//...
}
(The preceding declaration in your code is superfluous, as well as the extra semicolon in the for loop heading.)
(代码中的前面声明是多余的,以及 for 循环标题中的额外分号。)
Whether you use this syntax or the while
loop is a matter of taste, both translate to exactly the same. The generic syntax of the for loop is:
无论您使用这种语法还是while
循环是一种品味问题,两者都转化为完全相同。for 循环的通用语法是:
for (<init stmt>; <loop cond>; <iterate stmt>) { <body>; }
which is equivalent to:
这相当于:
<init stmt>;
while (<loop cond>) { <body>; <iterate stmt>; }
Edit:Actually, the above two forms are not entirely equivalent, if(as in the question) the variable is declared with the init statement. In this case, there will be a difference in the scope of the iterator variable. With the for loop, the scope is limited to the loop itself, in the case of the while loop, however, the scope extends to the end of the enclosing block (no big surprise, since the declaration is outside the loop).
编辑:实际上,上述两种形式并不完全等效,如果(如问题中所示)变量是用 init 语句声明的。在这种情况下,迭代器变量的范围会有所不同。对于 for 循环,作用域仅限于循环本身,而在 while 循环中,作用域扩展到封闭块的末尾(这并不奇怪,因为声明在循环之外)。
Also, as others have pointed out, in newer versions of Java, there is a shorthand notation for the for loop:
此外,正如其他人指出的那样,在较新版本的 Java 中,for 循环有一个速记符号:
for (Iterator<Foo> it = myIterable.iterator(); it.hasNext(); ) {
Foo foo = it.next();
//...
}
can be written as:
可以写成:
for (Foo foo : myIterable) {
//...
}
With this form, you of course lose the direct reference to the iterator, which is necessary, for example, if you want to delete items from the collection while iterating.
使用这种形式,您当然会失去对迭代器的直接引用,这是必要的,例如,如果您想在迭代时从集合中删除项目。
回答by tddmonkey
It's just a style thing and like you I prefer the for loop when using something with an index. If you're using Java 5 you should of course use a foreach loop over the collection anyway:
这只是一种风格,就像你一样,当使用带有索引的东西时,我更喜欢 for 循环。如果您使用的是 Java 5,您当然应该在集合上使用 foreach 循环:
Collection<String> someCollection = someCollectionOfString();
for (String element : someCollection) {
....
}
回答by Andrzej Doyle
People may use the explicit ('old style') for loop simply because it feels cleaner to them, perhaps they haven't adjusted to the new syntax yet (which I personally think is a lot cleaner).
人们可能会使用显式(“旧样式”)for 循环,只是因为他们感觉更干净,也许他们还没有适应新语法(我个人认为它更干净)。
One actual specific advantage of the longer for loop construct is that you have a reference to the iterator and so can call methods on it other then next()
. In particular, hasNext()
can often be useful to call - imagine if you want to print out a list of strings comma-separated:
较长的 for 循环构造的一个实际特定优势是您可以引用迭代器,因此可以在 then 之外调用它的方法next()
。特别是,hasNext()
调用通常很有用 - 想象一下,如果您想打印出以逗号分隔的字符串列表:
StringBuilder sb = new StringBuilder();
for (Iterator it=...; it.hasNext();){
sb.append(it.next());
if (it.hasNext())
sb.append(", ");
}
It is only to distinguish the "this is the last one" case like this if you use the more verbose for loop.
如果您使用更冗长的 for 循环,它只是为了区分“这是最后一个”的情况。
回答by Henrik Paul
There isn't much difference between those two methods, other than the first one remembers the value of it
after the loop. The second approach probably throws an error, because you redeclare the variable inside the loop.
这两种方法没有太大区别,除了第一个记住it
循环之后的值。第二种方法可能会引发错误,因为您在循环内重新声明了变量。
There's actually a third method to this, aswell. Instead of writing e.g.
实际上还有第三种方法。而不是写例如
for (Iterator<SomeObject> it = foo.iterator(); it.hasNext();) {
SomeObject so = foo.next();
}
you can most often write
你可以经常写
for (SomeObject so: foo) {...}
These two equal to the same thing...
这两个等同于同一个东西...
回答by matt b
The purpose of declaring the Iterator
within the for loop is to minimize the scope of your variables, which is a good practice.
Iterator
在 for 循环中声明 的目的是最小化变量的范围,这是一个很好的做法。
When you declare the Iterator
outside of the loop, then the reference is still valid / alive after the loop completes. 99.99% of the time, you don't need to continue to use the Iterator
once the loop completes, so such a style can lead to bugs like this:
当您声明Iterator
循环的外部时,循环完成后引用仍然有效/活动。99.99% 的情况下,Iterator
一旦循环完成,你就不需要继续使用了,所以这样的风格会导致这样的错误:
//iterate over first collection
Iterator it1 = collection1.iterator();
while(it1.hasNext()) {
//blah blah
}
//iterate over second collection
Iterator it2 = collection2.iterator();
while(it1.hasNext()) {
//oops copy and paste error! it1 has no more elements at this point
}