I'm studying for OCA certification and on the ArrayList
topic, after making some tests, I came across the following issue:
import java.util.ArrayList;
public class ArrayLists{
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(1);
list.add("hi");
// Passing a non-Generics list to a Generics list
ArrayList<String> list2 = new ArrayList<>(list);
for(int i = 0; i < list2.size(); i++) {
System.out.println(list2.get(i));
}
// error, cannot cast Integer to string
for(String s : list2) {
System.out.println(s);
}
}
}
Why does Java compile this behavior, since I'll get a runtime error running the program?