Given the following not-very-useful code:
package com.something;
import java.util.ArrayList;
import java.util.Collectio
The 2nd call to fancy() is a compiler error because Java can't infer any common type between the two arguments (can't infer Object since the second parameter must be a Collection.)
Well, I am not sure this is the reason, I would say the reason is that the generic type T
in Collection
is an invariant whose value determines the type of the first parameter T
.
For instance, this is valid:
fancy("", new ArrayList()); //compiles Ok
Because all String
are CharSequences
. It is expected that the first parameter is a CharSequence
once the type is inferred from ArraysList
.
However, this is not valid:
fancy((CharSequence)"", new ArrayList()); //compiler error
Because it is expected the type of the first parameter be String
, and we cannot ensure that all CharSequences
are, in fact, of type String
, right?
So, AFAIK, the reason the types are not compatible is due to the nature of generics in this case, and not to the fact that the second type is a Collection
.