class Test<G extends String>{
public G test(){return null;}
public List<G> tests(){return new ArrayList<>();}
}
public void doTest(Test t){
//works fine
String str = t.test();
//Compile error: expected String found Object
str = t.tests().iterator().next();
}
我希望最后一行返回一个 String 实例而不是 Object,因为类型 G 绑定(bind)到子类 String。除了强制转换还有其他方法吗?
最佳答案
不,该类型已被删除。您遇到了两种不同的类型删除规则 - 来自 JLS section 4.6 :
- The erasure of a parameterized type (§4.5) G is |G|.
- The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
所以删除List<G>
是 List
,但删除 G
是 String
- 这就是第一个作业成功的原因。
要编译此代码,您所需要做的就是在参数中使用通配符:
public void doTest(Test<?> t)
关于java - 为什么集合的未定义泛型类型默认为 Object,即使绑定(bind)到其他类也是如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24171300/