在Java中使用'for' [英] Uses of 'for' in Java

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

问题描述

我对Java相当陌生,在另一个关于 for循环回答说在Java中有for的两种用法:
$ b $ $ $ $ $ $ $ $ $ $ $ for(int i = 0; (< N; i ++){
}


for(String a:anyIterable){
}

我知道第一次使用for并且使用了很多,但是我从未见过第二个。什么是以前做什么和什么时候使用它?

解决方案您指定的两个中的第一个是的经典C 循环。这给程序员控制迭代标准,并允许三个操作:初始化;循环测试;增量表达式。虽然它经常被用来递增地重复一定次数的尝试,例如:/ b>

  for(int i = 0 ; i   

代码中的 for 用于迭代集合:

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

为了避免第二种类型子句通常是未使用的),并赞扬引入的泛型 Java 1.5,你的两个例子中的第二个 - 增强的for循环,或者 for-each loop

第二个用于数组和泛型集合。 请参阅此文档。它允许你迭代一个通用的集合,在那里你知道 Collection 的类型,而不必转换 Iterator.next的结果)到一个已知的类型。



比较:

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

对于(String myStr:myList){
//...do myStr
} b

  $ b  

此循环的新样式也可以用于数组:

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


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) {
}

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?

解决方案

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++)

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

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 Generics introduced in Java 1.5, the second of your two examples - the enhanced for loop, or the for-each loop - was introduced.

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.

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:

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

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

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