Generics are used only by the compiler to provide type safety and eliminate any unwanted casts. However, the compiled code doesn't store the additional information (only to to provide compatibility with legacy code).
In your case, for example, at runtime your code creates an ArrayList of Objects, and not an ArrayList of Integers, how you may have expected.
You may also check that at runtime, regardless of the inferred type, they all have the same class:
You may also look up "generics type erasure" for additional info.
Yes, this time the compiler sees that you are trying to add a String into a Collection of Integers, thus the compile time error.
The difference is that earlier, you were adding Strings and Integers into a Collection of Objects, which doesn't mind the compiler.
Joined: Jul 25, 2011
Thanks. Won't say its absolutely clear .... I think I will need to read and try type erasure in detail to understand it completely. Have some idea for now.