gpt4 book ai didi

java - 为什么未定义的泛型类型的集合默认为对象,即使绑定(bind)到其他类?

转载 作者:行者123 更新时间:2023-11-30 06:18:41 25 4
gpt4 key购买 nike

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 , 但删除 GString - 这就是第一个作业起作用的原因。

要编译此代码,您需要做的就是在参数中使用通配符:

public void doTest(Test<?> t)

关于java - 为什么未定义的泛型类型的集合默认为对象,即使绑定(bind)到其他类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24171300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com