In generics, the generic type T must match the method declaration. So for your generic declaration Collection<T>, you can pass:
- Collection<SubtypeT> // won't compile
- SubtypeCollection<SubtypeT> // won't compile
On the other hand for arrays, you can pass an object of a subtype. For your array declaration T, you can pass:
For the code to compile properly, you have to modify the Collection declaration to accept T or its subtype like this:
Muneeswaran Balasubramanian wrote:Hi Faraz,
If i change the second method like
its compiles fine.I think its conflict with your statement,
Ikpefua Jacob-Obinyan wrote:@Andreas,
You are excelently correct, the 'String' is "widened" to 'Object' during invocation.
Java simply does NOT 'implicitly' allow "widening" in collections, you must tell it to with this syntax:
so if you modify the genericMethod() like this:
The code compiles without problems
You have read my mind ! This is exactly the question I was trying to ask but I could not have put it better than you have. I am also pretty sure that I will not be able to spot this in the real exam unless I know exactly how <T> is ascertained.
Hope we can get a good answer now