Java 中“for"的使用 [英] Uses of 'for' in Java

查看:19
本文介绍了Java 中“for"的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


for (String a : anyIterable) {
}

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

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?

推荐答案

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

The first of the two you specify is a classic C for loop. 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:

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

在代码中还有更多使用 for 来迭代集合的实例:

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

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

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

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

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

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.

比较:

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

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

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

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

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

这篇关于Java 中“for"的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆