Java 中“for”的使用

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

Uses of 'for' in Java

javaloopsfor-loop

提问by Josh Curren

I am fairly new to Java and in another Stack Overflow question about for loopsan answer said that there was two uses of for in Java:

我对 Java 还很陌生,在另一个关于for 循环的Stack Overflow 问题中答案说在 Java 中有两种 for 用法:

for (int i = 0; i < N; i++) {
}


for (String a : anyIterable) {
}

I know the first use of for and have used it a lot, but I have never seen the second one. What is it used to do and when would I use it?

我知道 for 的第一个用法并且用过很多次,但是我从来没有见过第二个。它用来做什么以及我什么时候使用它?

采纳答案by akf

The first of the two you specify is a classic C forloop. This gives the programmer control over the iteration criteria and allows for three operations: the initialization; the loop test ; the increment expression. Though it is used often to incrementally repeat for a set number of attempts, as in yor example:

您指定的两个中的第一个是经典的 Cfor循环。这使程序员可以控制迭代标准并允许进行三种操作:初始化;循环测试;增量表达式。虽然它经常用于递增重复一定次数的尝试,如您的示例:

for (int i=0; i < N : i++)

There are many more instances in code where the forwas use to iterate over collections:

代码中有更多实例for用于迭代集合:

for (Iterator iter = myList.iterator(); iter.hasNext();)

To aleviate the boilerplating of the second type (where the third clause was often unused), and to compliment the Genericsintroduced in Java 1.5, the second of your two examples - the enhanced for loop, or the for-each loop- was introduced.

为了减轻第二种类型的样板(其中第三个子句通常未使用),并补充Java 1.5 中引入的泛型,引入了两个示例中的第二个 - 增强的 for 循环,或for-each loop- 。

The second is used with arrays and Generic collections. See this documentation. It allows you to iterate over a generic collection, where you know the type of the Collection, without having to cast the result of the Iterator.next()to a known type.

第二个用于数组和通用集合。 请参阅此文档。它允许您遍历泛型集合,其中您知道 的类型Collection,而不必将 的结果Iterator.next()转换为已知类型。

Compare:

相比:

for(Iterator iter = myList.iterator; iter.hasNext() ; ) {
   String myStr = (String) iter.next();
   //...do something with myStr
}

with

for (String myStr : myList) {
   //...do something with myStr
 }

This 'new style' for loop can be used with arrays as well:

这种“新风格”的 for 循环也可以用于数组:

String[] strArray= ...
for (String myStr : strArray) {
   //...do something with myStr
}

回答by Paul

It's used to iterate through an entire array or Iterable collection. It basically replaces:

它用于遍历整个数组或 Iterable 集合。它基本上取代了:

for(int i=0; i<N.length; i++)

And can be used with Generics which is quite cool

并且可以与泛型一起使用,这很酷

回答by wm_eddie

The "for in" loop is mostly eye-candy that makes code easier to read. (If you pronounce the : as "in").

“for in”循环主要是吸引人的,它使代码更易于阅读。(如果您将 : 发音为“in”)。

I use the second type almost exclusively in my own code whenever I'm iterating over a list or array.

每当我迭代列表或数组时,我几乎只在自己的代码中使用第二种类型。

I still use the regular for loop when dealing with mostly mathematical code, or when I need an "i" to see how many times I've looped.

在处理大部分数学代码时,或者当我需要一个“i”来查看我循环了多少次时,我仍然使用常规 for 循环。

回答by Chris Thompson

It's called a for each loop and basically, it can be used with anything that implements

它被称为 for each 循环,基本上,它可以用于任何实现

java.lang.Iterable

Generic collections implement this interface, but you could make your own class that did as well. It makes dealing with everything in a list/collection very easy although the downside is that you don't get explicit access to the current number in the list like you do in the traditional loop. There is some additional overhead associated with this type of loop over traditional loops because of the calls to the iterator classes.

通用集合实现了这个接口,但你也可以创建自己的类。它使处理列表/集合中的所有内容变得非常容易,尽管缺点是您无法像在传统循环中那样显式访问列表中的当前数字。由于对迭代器类的调用,与传统循环相比,这种类型的循环会产生一些额外的开销。

回答by RoshanS

Both of them are same in functionality , but for (String a : anyIterable) {}, is more readable ,less typing and shorter. for (int i=0; i < N : i++)index the collection , by loop control variable iand for (String a : anyIterable) {}does not index the collection

它们在功能上是相同的,但是 对于 (String a : anyIterable) {} 来说,可读性更好,打字更少,更短。 for (int i=0; i < N : i++)索引集合,通过循环控制变量 ifor (String a : anyIterable) {}不索引集合