Java - Browsing an ArrayList with the for-each loop

We saw how to do the scan in an ArrayList. In this tutorial, we'll learn how to browse ArrayList with the advanced for loop abbreviated as for-each.

import java.util.ArrayList; 
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;

public class parcourslist {

public static void main(String[] args) {

ArrayList< String> list = new ArrayList< String> ();
list.add("o1");
list.add("22");
list.add("o3");

for(String s : list)
System.out.println(s);
}
}
o1
o2
o3
The for-each loop throws an error if the ArrayList to be browsed does not have a generic type. For example, we'll remove the genericity in ArrayList:

ArrayList list = new ArrayList(); 
The java compiler considers that the elements of our ArrayList are objects without any type and that it cannot convert them to String:

foreach java ArrayList