java泛型编译问题:不兼容类型
考虑到这个简单的类:
import java.util.Collection;
public class GenericTest<T> {
public Collection<String> getKeys() {
return null;
}
public void copy(GenericTest a_from) {
for (String x : a_from.getKeys()) {
}
}
}
我得到以下编译错误,但不明白为什么
error: incompatible types
for (String x : a_from.getKeys()) {
required: String
found: Object
如果我将copy()方法的参数改为GenericTest<;T>;,但这不是我想要的。copy()方法对任何类型的GenericTest都有效,而不仅仅是GenericTest<;T>
# 1 楼答案
这不是创建泛型类的方式。如果使用泛型类的原始类型,那么类中使用的所有参数化类型都会丢失其类型信息。因此,对于
GenericTest
raw类型,getKeys()
方法签名更改为:所以,如果你在
GenericTest
raw类型的getKeys()
方法上迭代,你会得到Object
,而不是String
,我不明白你为什么期望这样从JLS Section 4.8 - Raw Types
您应该在方法中使用
GenericTest<T>
作为参数类型,而不是原始类型。并将getKeys
的返回类型更改为Collection<T>
将课程改为:
类型
T
是从您为此泛型类创建的参数化类型推断出来的。对于GenericTest<String>
,T
将在您的类中被推断为String
参考: