【问题标题】:Difference between <? extends CustomClass> and <CustomClass> Genericity<? 之间的区别扩展 CustomClass> 和 <CustomClass> 通用性
【发布时间】:2013-11-20 10:11:41
【问题描述】:

这些List有什么区别。

ArrayList<? extends CustomClass> test = new ArrayList<CustomClass>();
ArrayList<CustomClass> test2= new ArrayList<CustomClass>();

或在这两个类之间。

class test <T extends CustomClass> {

 public void <T> someThings(T arg){}

}

class test {

 public void someThings(CustomClass arg){}

}

T 扩展了CustomClass,因此在someThings() 方法中使用CustomClass 的子类作为参数应该可以工作。

但它与第二种情况完全相同,我们也可以将CustomClass 的子类作为参数传递。

这两个解决方案之间的确切区别是什么?

【问题讨论】:

    标签: java list class generics design-patterns


    【解决方案1】:

    如果你有子类:

    public class SuperClass {
    }
    
    public class SubClass extends SuperClass {
    }
    

    然后:

    List<? extends SuperClass> test1 = new ArrayList<SubClass>(); // ok
    List<SuperClass> test2 = new ArrayList<SubClass>(); // ko, won't compile
    

    发送消息Type mismatch: cannot convert from ArrayList&lt;SubClass&gt; to ArrayList&lt;SuperClass&gt;


    参数化方法时,真正之间没有区别:

    public <T extends SuperClass> void method(T arg)
    

    还有:

    public void method(SuperClass arg)
    

    在返回上述类型时参数化方法很有趣:

    public <T extends SuperClass> T method(T arg)
    

    【讨论】:

    • 好的,但是在我们以这种方式实例化 List 的情况下 List test2 = new ArrayList();与 List test1 = new ArrayList();
    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 2017-10-30
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2021-10-12
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多