Java 使用 for 循环还是 while 循环进行迭代?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/99164/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:16:54  来源:igfitidea点击:

Iterate with for loop or while loop?

javafor-loopiterator

提问by James A. N. Stauffer

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:

但我这样写(当 Java 1.5 不可用或不能使用 Java 1.5 时)为:

for(Iterator i = list.iterator(); i.hasNext(); ) {
    ...
}

because

因为

  • It is shorter
  • It keeps iin a smaller scope
  • It reduces the chance of confusion. (Is iused outside the while? Where is ideclared?)
  • 它更短
  • 它保持i在较小的范围内
  • 它减少了混淆的机会。(是i在while之外使用的?i声明在哪里?)

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

来自:http: //jamesjava.blogspot.com/2006/04/iterating.html

采纳答案by Lou Franco

I prefer the for loop because it also sets the scope of the iterator to just the for loop.

我更喜欢 for 循环,因为它还将迭代器的范围设置为仅 for 循环。

回答by scubabbl

Either is fine. I use for () myself, and I don't know if there are compile issues. I suspect they both get optimized down to pretty much the same thing.

哪个都好。我自己用for(),不知道有没有编译问题。我怀疑它们都被优化为几乎相同的东西。

回答by Steven A. Lowe

if you're only going to use the iterator once and throw it away, the second form is preferred; otherwise you must use the first form

如果您只打算使用迭代器一次然后将其丢弃,则首选第二种形式;否则你必须使用第一种形式

回答by Giorgio Galante

Why not use the for-each construct? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too):

为什么不使用 for-each 结构?(我有一段时间没有使用 Java,但它存在于 C# 中,我很确定 Java 1.5 也有这个):

List<String> names = new ArrayList<String>();
names.add("a");
names.add("b");
names.add("c");

for (String name : names)
    System.out.println(name.charAt(0));

回答by Guy Starbuck

I would agree that the "for" loop is clearer and more appropriate when iterating.

我同意“for”循环在迭代时更清晰、更合适。

The "while" loop is appropriate for polling, or where the number of loops to meet exit condition will change based on activity inside the loop.

“while”循环适用于轮询,或者满足退出条件的循环数将根据循环内的活动而改变。

回答by Dima

I think scope is the biggest issue here, as you have pointed out.

正如您所指出的,我认为范围是这里最大的问题。

In the "while" example, the iterator is declared outside the loop, so it will continue to exist after the loop is done. This may cause issues if this same iterator is used again at some later point. E. g. you may forget to initialize it before using it in another loop.

在“while”示例中,迭代器是在循环外声明的,因此在循环完成后它将继续存在。如果稍后再次使用相同的迭代器,这可能会导致问题。例如 在另一个循环中使用它之前,您可能忘记初始化它。

In the "for" example, the iterator is declared inside the loop, so its scope is limited to the loop. If you try to use it after the loop, you will get a compiler error.

在“for”示例中,迭代器是在循环内声明的,因此其作用域仅限于循环。如果您尝试在循环之后使用它,则会出现编译器错误。

回答by Ron Savage

Although both are really fine, I tend to use the first example because it is easier to read.

尽管两者都很好,但我倾向于使用第一个示例,因为它更易于阅读。

There are fewer operations happening on each line with the while() loop, making the code easier for someone new to the code to understand what's going on.

使用 while() 循环在每一行上发生的操作更少,这使得代码新手更容易理解正在发生的事情。

That type of construct also allows me to group initializations in a common location (at the top of the method) which also simplifies commenting for me, and conceptualization for someone reading it for the first time.

这种类型的构造还允许我在一个公共位置(在方法的顶部)对初始化进行分组,这也简化了我的评论,以及第一次阅读它的人的概念化。

回答by Svet

I agree that the for loop should be used whenever possible but sometimes there's more complex logic that controls the iterator in the body of the loop. In that case you have to go with while.

我同意应该尽可能使用 for 循环,但有时有更复杂的逻辑来控制循环体中的迭代器。在这种情况下,您必须使用 while。

回答by Jon Limjap

There are appropriate uses for the while, the for, and the foreach constructs:

while、for 和 foreach 结构有适当的用途:

  • while- Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition

  • for- Use this if you are looping and your primary concern is the index of the array/collection/list. It is more useful to use a for if you are most likely to go through allthe elements anyway, and in a particular order (e.g., going backwards through a sorted list, for example).

  • foreach- Use this if you merely need to go through your collection regardless of order.

  • while- 如果您正在迭代并且循环与否的决定因素仅基于条件,请使用此选项。在这个循环结构中,保持索引只是次要问题;一切都应该基于条件

  • for- 如果您正在循环并且您主要关心的是数组/集合/列表的索引,请使用此选项。如果您最有可能以特定顺序遍历所有元素(例如,向后遍历排序列表),则使用 for 会更有用。

  • foreach- 如果您只需要浏览您的收藏而不管顺序如何,请使用此选项。

Obviously there are exceptions to the above, but that's the general rule I use when deciding to use which. That being said I tend to use foreachmore often.

显然,上面有例外,但这是我在决定使用哪个时使用的一般规则。话虽如此,我倾向于foreach更频繁地使用。

回答by Jon Limjap

I was the for loop for clarity. While I use the while loopwhen faced with some undeterministic condition.

为了清楚起见,我是 for 循环。当我遇到一些不确定的情况时,我会使用while 循环