这两个示例不能使用Oracle Java 8 JDK进行编译。
错误是:
错误:不兼容的类型:对象无法转换为整数 for (整数 i : foo.set (
例1(
import java.util.Set;
class Foo<T>
{
protected Set<Integer> set;
}
class Foo2 extends Foo
{
void doit()
{
for (Integer i : set )
{
}
}
}
例2(
import java.util.Set;
class Foo<T>
{
public Set<Integer> set;
public static void main( String[] args )
{
Foo foo = new Foo();
for (Integer i : foo.set )
{
}
}
}
是错误还是功能?据我所知,泛型在原始类型字段中不起作用。
这不是
错误。您需要传递泛型类型才能创建新实例:
class Foo<T>
{
public Set<Integer> set;
public static void main( String[] args ) {
Foo<Integer> foo = new Foo(); // changed code
for (Integer i : foo.set )
{
}
}
}