Example of the foreach loop in Java
The foreach loop (called "enhanced for loop or advanced for loop") has been integrated since Java 5, is equivalent to java.util.Iterator. So, when reading an element, one by one in order, the foreach loop is the right choice, because it is more convenient.Foreach syntax
The foreach loop is used to iterate through arrays as well as collections of objects.
Example:for(variable type: Table | collection){
.
.
}
for(String s : listString) {
System.out.println(s);
}
Traversing an array with foreach in java
public class Loops {Output:
public static void main(String[] args) {
String[] tstring = {"aa","ab","ac","ad","ae"};
for(String s: tstring)
System.out.println(s);
}
}
aa
ab
ac
ad
ae
Object Collection Path with foreach
public class Parcours_List_foreach {Runtime:
public static void main( String[] args) {
ArrayListarraylist = new ArrayList ();
arraylist.add("e1");
arraylist.add("e2");
arraylist.add("e3");
arraylist.add("e4");
for(String s : arraylist){
System.out.println(s);
}
}
}
e1
e2
e3
e4
Note: There are situations where you need to use Iterator directly, for example, deleting an item using foreach may cause an exception. ConcurrentModificationException. |
IteratorReferences:iterator = list.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
JavaDoc: The For-Each Loop