test1和test2的区别在哪里? 为什么test1编译出错?
import java.util.ArrayList;
import java.util.Collection;
class MyType {
}
class MyClass<T> {
private Collection<MyType> myTypes = new ArrayList<MyType>();
private Collection<T> myTs = new ArrayList<T>();
public Collection<MyType> getMyTypes() {
return myTypes;
}
public Collection<T> getMyTs() {
return myTs;
}
}
public class TestSimple {
public void test1() {
MyClass myClass = new MyClass();
for (MyType myType : myClass.getMyTypes()) {
}
}
public void test2() {
MyClass myClass = new MyClass();
Collection<MyType> myTypes = myClass.getMyTypes();
for (MyType myType : myTypes) {
}
}
public void test3() {
MyClass<Long> myClass = new MyClass<Long>();
for (Long myType : myClass.getMyTs()) {
}
}
}
最佳答案
如果您在一个类上定义了一个通用约束,然后在不提供任何通用约束的情况下实例化该类(也就是说,您完全离开了 <>
),那么您就进入了 Raw Types 的领域。 ,一切都不再一样了。
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.
根据 Angelika Langer 的优秀 Java Generics FAQ ,
Methods or constructors of a raw type have the signature that they would have after type erasure. A method or constructor call to a raw type generates an unchecked warning if the erasure changes the argument types.
所以通过构建MyClass
作为原始类型(即 MyClass
而不是 MyClass<?>
),您已完全选择退出泛型,返回类型为 getMyTypes()
现在是原始类型 Collection
,而不是 Collection<MyType>
.因此,您无法使用增强的 for
类型为 MyType
的语法, 你必须使用 Object
相反。
当然,更好的解决方案就是使用MyClass<?>
(而不仅仅是 MyClass
)当你的意思是 MyClass
未知参数化类型。
关于java - 泛型编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7423150/