Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

loops - Uses of 'for' in Java

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...