Consider the following...
Now... imagine this was an exam question... Options could be:
1: Code compiles and runs, printing first the Integer then the String inside the list.
2: The code compiles but throws a runtime exception.
3: The code fails to compile.
Right... this is purely my own creation, inspired from a textbook question. The problem for me here, is that if you run this code, there will be a ClassCastException thrown at runtime. The underlying question is, why does this happen when the enhanced for loop is expecting (casting) the instances in the list to Object and not Integer?
At first I thought it was because 1: the list is created as an <Integer> generic type, meaning that the compiler automatically inserts casts to Integer whenever we try to extract something from it. This together with 2: the enhanced for loop really uses the Interator mechanic, and since the generic type of the list is <Integer>, then so is the Iterator (working behind the scenes of the enhanced for loop). Meaning there is an invisible cast to Integer by the invisible Iterator, behind the for loop.
BUT (and here's what really confuses me), if we remove the for loop, and uncomment the Iterator lines above it, the code runs fine! (compiles with warnings due to the add() method, but it runs perfectly and prints the objects). Even though the Iterator is defined as having generic type <Integer> !
The 2 questions this boils down to are...
1: Why does the enhanced for loop cause an exception, even though we're casting the objects to Object?
2: Why does the Iterator NOT throw an exception, even though it is defined as generic type <Integer>? I think this should imply a behind the scenes casting to Integer, but obviously it doesn't?
// Andreas