Mike Schilling wrote:
for (String s : getOddity(list, String.class)) // ******
Tom Anderson wrote:
If you write this:
Iterable<String> oddity = getOddity(list, String.class);
for (String s : oddity)
it works. I can't say why, but perhaps the rules are written in terms
of inference from the types of variables, rather than expressions?
Mike Schilling wrote:
That compiles for me, but with the warning
Note: C:\java\Stuff\src\Oddity.java uses unchecked or unsafe operations.
IntelliJ gives a bit more detail:
Unchecked assignment from Iterable to Iterable<String>
So the type inference still fails, but now in a way that javac considers
forgivable.
You can't infer the generic type from the raw type. So it's not type
inference here but type conversion.
The original method:
public static<T,C> Iterable<C> getOddity(Collection<T> coll, Class<C>
clazz)
{
return null;
}
was passed a raw-typed 'coll' argument. This gives no information about
what 'T' is.
When the collection type became non-raw with the '<?>' generic parm, then
the type inference engine had enough to work with.
Why it couldn't ignore the 'T' and infer the 'C' is a mystery, but clearly
connected with having broken the whole generics thing with a raw type in
the first place. Apparently once the foundation is cracked the entire
edifice is unstable.
That does appear to be the case. I don???t think the JLS helps here, but it's