分享

class<T>和 class<?>类型 有什么区别

 yliu277 2019-07-23
第一种是固定的一种泛型,第二种是只要是Object类的子类都可以,换言之,任何类都可以,因为Object是所有类的根基类
固定的泛型指类型是固定的,比如:Interge,String. 就是<T extends Collection>

<? extends Collection> 这里?代表一个未知的类型,
但是,这个未知的类型实际上是Collection的一个子类,Collection是这个通配符的上限.
举个例子
class Test <T extends Collection> { }

<T extends Collection>其中,限定了构造此类实例的时候T是一个确定类型(具体类型),这个类型实现了Collection接口,
但是实现 Collection接口的类很多很多,如果针对每一种都要写出具体的子类类型,那也太麻烦了,干脆还不如用
Object通用一下。
<? extends Collection>其中,?是一个未知类型,是一个通配符泛型,这个类型是实现Collection接口即可。

_________________________上面讲的是什么鬼,当你知道引入通配符泛型的由来之后(下面代码由java1234.com提供)_________________________________________________________________________________________

The method take(Animal) in the type Test is not applicable for the arguments (Demo<Dog>)
The method take(Animal) in the type Test is not applicable for the arguments (Demo<Cat>)
The method take(Animal) in the type Test is not applicable for the arguments (Demo<Animal>)

当引入泛型之后,遇到这种情况,参数怎么写都不适合,总有2个方法不适用,为了给泛型类写一个通用的方法,这时候就需要引入了 ?通配符的概念。



复制代码
public class Demo <T extends Animal>{ private T ob; public T getOb() { return ob; } public void setOb(T ob) { this.ob = ob; } public Demo(T ob) { super(); this.ob = ob; } public void print(){ System.out.println('T的类型是:' ob.getClass().getName()); } }
复制代码

参考:

https://www.cnblogs.com/lwbqqyumidi/p/3837629.html

                                    

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多