While
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class WhileIteration {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<String>();
collection.add("zero");
collection.add("one");
collection.add("two");
Iterator iterator = collection.iterator();
// while loop
while (iterator.hasNext()) {
System.out.println("value= " + iterator.next());
}
}
}
For
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class ForIteration {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<String>();
collection.add("zero");
collection.add("one");
collection.add("two");
// for loop
for (Iterator<String> iterator = collection.iterator(); iterator.hasNext();) {
System.out.println("value= " + iterator.next());
}
}
}
For-Each
import java.util.ArrayList;
import java.util.Collection;
public class ForEachInteration {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<String>();
collection.add("zero");
collection.add("one");
collection.add("two");
// for-each loop
for (String s : collection) {
System.out.println("value= " + s);
}
}
}
The result for each method should look like this:
value= zero
value= one
value= two
2 comments:
Hmm... I have not actively used Java for some time now, even though I am a certified Java programmer. But I guess you learn something every day.
The for-each loop looks cool, but I wonder who had the need to make that a part of the language.
The for, while and do-while loops were completely sufficient to do anything you needed to.
The for-each loop looks like a plain old VB structure.
I hope they do not pull towards the crappy VB syntax and continue the C/C++ syntax.
Post a Comment