I think it is not due to legacy code; the problem is elsewhere. Here, JVM generates the following exception:
Sahil Kapoor
Varun Kapoor
Exception in
thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
At TestLegacy.main(TestLegacy.java:14)
From the above for-each loop, we can apparently think that the element of the myList, what is either String or Integer should assign into Object reference normally. But, I feel there is an intermediate step that try to cast the element of the myList into the actual parameter type with which the myList is declared and instantiated. And then the reference of the element is assigned into the Object reference.
Another part of the story is that if we use Iterator<E> instead of for-each loop then we will get the expected result. For instance,
Vary interesting!