简体   繁体   English

用for循环或while循环迭代?

[英]Iterate with for loop or while loop?

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不可用或者每个都不能使用时):

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

because 因为

  • It is shorter 它更短
  • It keeps i in a smaller scope 它让i的范围更小
  • It reduces the chance of confusion. 它减少了混淆的可能性。 (Is i used outside the while? Where is i declared?) i是否在外面使用? 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

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

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. while - 如果您正在迭代,请使用此选项,并且循环的决定因素是否仅基于条件。 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. for - 如果您正在循环,请使用此选项,主要关注的是数组/集合/列表的索引。 It is more useful to use a for if you are most likely to go through all the elements anyway, and in a particular order (eg, going backwards through a sorted list, for example). 如果您最有可能通过所有元素并以特定顺序(例如,通过排序列表向后),则使用for更有用。

  • foreach - Use this if you merely need to go through your collection regardless of order. 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 foreach more often. 话虽如此,我倾向于更频繁地使用foreach

Why not use the for-each construct? 为什么不使用for-each构造? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too): (我有一段时间没有使用过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));

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. 在“while”示例中,迭代器在循环外声明,因此在循环完成后它将继续存在。 This may cause issues if this same iterator is used again at some later point. 如果稍后再次使用相同的迭代器,这可能会导致问题。 E. g. E. g。 you may forget to initialize it before using it in another loop. 在另一个循环中使用它之前,您可能会忘记初始化它。

In the "for" example, the iterator is declared inside the loop, so its scope is limited to the loop. 在“for”示例中,迭代器在循环内声明,因此其范围仅限于循环。 If you try to use it after the loop, you will get a compiler error. 如果在循环后尝试使用它,则会出现编译器错误。

IMHO, the for loop is less readable in this scenario, if you look at this code from the perspective of English language. 恕我直言,如果你从英语语言的角度来看这个代码,那么for循环在这种情况下的可读性较差。 I am working on a code where author does abuse for loop, and it ain't pretty. 我工作的一个代码,其中作者不滥用for循环,这是不漂亮。 Compare following: 比较以下:

for (; (currUserObjectIndex < _domainObjectReferences.Length) && (_domainObjectReferences[currUserObjectIndex].VisualIndex == index); ++currUserObjectIndex)
    ++currNumUserObjects;

vs VS

while (currUserObjectIndex < _domainObjectReferences.Length && _domainObjectReferences[currUserObjectIndex].VisualIndex == index)
{
    ++currNumUserObjects;
    ++currUserObjectIndex;
}

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 否则你必须使用第一个表格

Using for loop you can work with a single variable, as it sets the scope of variable for a current working for loop only. 使用for循环可以使用单个变量,因为它只为当前工作循环设置变量的范围。 However this is not possible in while loop . 然而,这在while循环中是不可能的 For Example: 例如:
int i; int i; for(i=0; in1;i++) do something.. for(i = 0; in1; i ++)做某事......

for(i=0;i n2;i+=2) do something. for(i = 0; i n2; i + = 2)做某事。

So after 1st loop i=n1-1 at the end. 所以在第一次循环后i = n1-1结束。 But while using second loop you can set i again to 0. However 但是在使用第二个循环时,您可以将i再次设置为0. 但是

int i=0; int i = 0;

while(i less than limit) { do something ..; 虽然(我不到限制){做某事......; i++; 我++; } }

Hence i is set to limit-1 at the end. 因此我最后设置为限制-1。 So you cant use same i in another while loop. 所以你不能在另一个while循环中使用相同的i。

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”循环适用于轮询,或者满足退出条件的循环数将根据循环内的活动而改变。

Not that it probably matters in this case, but Compilers, VMs and CPU's normally have special optimization techniques they user under the hood that will make for loops performance better (and in the near future parallel), in general they don't do that with while loops (because its harder to determine how it's actually going to run). 并不是说在这种情况下它可能很重要,但编译器,虚拟机和CPU通常都有特殊的优化技术,它们可以使用更好的循环性能(并且在不久的将来并行),通常他们不会这样做while循环(因为它更难确定它实际上将如何运行)。 But in most cases code clarity should trump optimization. 但在大多数情况下,代码清晰度应该胜过优化。

Both are fine, but remember that sometimes access to the Iterator directly is useful (such as if you are removing elements that match a certain condition - you will get a ConcurrentModificationException if you do collection.remove(o) inside a for(T o : collection) loop). 两者都很好,但请记住,有时直接访问Iterator是有用的(例如,如果要删除符合特定条件的元素 - 如果在for(T o:中)执行collection.remove(o),则会得到ConcurrentModificationException。集合)循环)。

I prefer to write the for(blah : blah) [foreach] syntax almost all of the time because it seems more naturally readable to me. 我更喜欢在几乎所有时间都写出for(blah:blah)[foreach]语法,因为它对我来说似乎更自然。 The concept of iterators in general don't really have parallels outside of programming 迭代器的概念通常与编程之外没有相似之处

Academia tends to prefer the while-loop as it makes for less complicated reasoning about programs. 学术界倾向于选择while循环,因为它使得对程序的推理更简单。 I tend to prefer the for- or foreach-loop structures as they make for easier-to-read code. 我倾向于选择for-或foreach-loop结构,因为它们使代码更容易阅读。

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. 我怀疑它们都被优化到几乎相同的东西。

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

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. 我同意尽可能使用for循环,但有时会有更复杂的逻辑来控制循环体中的迭代器。 In that case you have to go with while. 在那种情况下,你必须与时俱进。

I was the for loop for clarity. 为清晰起见,我是for循环。 While I use the while loop when faced with some undeterministic condition. 虽然我在遇到一些不确定的情况时会使用while循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM