M
Mike Schilling
While constructing the FilteredCollection class, I ran into the following
oddity with type inference. The following class fails to compile (using
javac 1.6.0_20):
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class Oddity<C> implements Iterable<C>
{
public Iterator<C> iterator()
{
return null;
}
public static void main(String[] args)
{
List list = Arrays.asList(1, "a", false);
for (String s : getOddity(list, String.class)) // ******
{
}
}
public static<T,C> Iterable<C> getOddity(Collection<T> coll, Class<C>
clazz)
{
return null;
}
}
The error, at the starred line, is
incompatible types
found : java.lang.Object
required: java.lang.String
That is, it looks as if the inference that getOddity should return an
Iterable<String> fails.
However, it works perfectly if the declaration of "list" in the previous
line is changed to
List<?> list
What's the deal here? Does the presence of a raw type interfere with type
inference?
oddity with type inference. The following class fails to compile (using
javac 1.6.0_20):
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class Oddity<C> implements Iterable<C>
{
public Iterator<C> iterator()
{
return null;
}
public static void main(String[] args)
{
List list = Arrays.asList(1, "a", false);
for (String s : getOddity(list, String.class)) // ******
{
}
}
public static<T,C> Iterable<C> getOddity(Collection<T> coll, Class<C>
clazz)
{
return null;
}
}
The error, at the starred line, is
incompatible types
found : java.lang.Object
required: java.lang.String
That is, it looks as if the inference that getOddity should return an
Iterable<String> fails.
However, it works perfectly if the declaration of "list" in the previous
line is changed to
List<?> list
What's the deal here? Does the presence of a raw type interfere with type
inference?