Abhay Agarwal wrote:My guess is that type erasure happens at Step 2 -(Linking).
No, type erasure happens during compilation, which is ofcourse before runtime - before class loading, linking and initialization.
Sudhanshu Mishra wrote:What I was asking was when do we know that the tyoe erasure would come into picture?Does type erasure is done by the compiler as soon as it comes across a generic code, or the compiler first validates the while code and then erases the type?
The compiler will not erase the generics immediately; if the compiler would effectively ignore the generics, there would be no point in using generics at all. The compiler uses generics for type checking, but purely for type checking that can be done at compile time. When the type checks pass, then the compiler erases the generics.
Which overloaded version of a method is called, is determined at compile time, before the generics are erased. That's exactly why you see in your example that
overloadedMethod(Collection o) is called. The version that takes a
List<Number> does not match, because an
ArrayList<Integer> is not a
List<Number> (*). So, in that case, the generics are taken into account to check which method should be called.
(*) If you would change the method to take a
List<? extends Number>, it would call the List version.