Possible Duplicate:
Why is List<Number> not a sub-type of List<Object>?
Isn’t String a subtype of Object in Java?
Then, how come I cannot pass an object of type List<String> into a function that accepts List<Object> as a parameter? I can, though, pass such an object into a function that accepts List as a parameter.
Yes it is, but that doesn’t make
List<String>a subtype ofList<Object>.Consider this example:
If (hypothetically)
List<String>was subtype ofList<Object>, then you’d end up assigning aIntegerto aStringvariable in the last statement. In short, we would have broken static type safety.Yes, that is true. But then you are dealing with raw types and you have to use explicit type casts when pulling objects out of the list. For example, the above would need to be rewritten as follows:
Note that the type-cast means we’ve had to replace static type-safety with runtime type-safety. (And, of course, in this case the typecast will fail at runtime because the instance has the wrong type.)