迭代for循环或while循环? [英] Iterate with for loop or while loop?
本文介绍了迭代for循环或while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Iterator i = list.iterator();
while(i.hasNext()){
...
}
但是我写的是(当Java 1.5不可用或者每个都不能使用时):
for(Iterator i = list.iterator(); i.hasNext();){
...
}
$ b
因为
- 它比较短
-
i
在较小的范围内
- 它减少了混淆的可能性。 (
i
在
之外使用,而$i
声明在哪里)
- 它减少了混淆的可能性。 (
我认为代码应该尽可能简单易懂,以便我只需要制作复杂的代码就可以完成复杂的工作。你怎么看?哪个更好?
来自: http://jamesjava.blogspot.com/2006/04/iterating.html
解决方案
我更喜欢for因为它也将迭代器的作用域设置为for循环。
I often see code like:
Iterator i = list.iterator();
while(i.hasNext()) {
...
}
but I write that (when Java 1.5 isn't available or for each can't be used) as:
for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
because
- It is shorter
- It keeps
i
in a smaller scope - It reduces the chance of confusion. (Is
i
used outside the while? Where isi
declared?)
I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?
From: http://jamesjava.blogspot.com/2006/04/iterating.html
解决方案
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
这篇关于迭代for循环或while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文