38_泛型的通配符扩展应用

时间:2015-01-31 12:05:36   收藏:0   阅读:194
public static void printCollection(Collection<Object> cols){
    for(Object obj:cols){
        System.out.println(obj);
    }
    /**
    cols.add("string");//没错
    cols=new HashSet<Date>();//会报告错误!
    */
}

 

public static void printCollection(Collection<?> cols){
    for(Object obj:cols){
        System.out.println(obj);
    }
    /**
    cols.add("string");//错误,因为他不知道自己未来匹配就一定是Stirng
    cols.size();//没错,此方法与类型参数没有关系
    cols=new HashSet<Date>();//没错,可以和 Collection<?>画等号
    */
}

技术分享

上图中,大红叉的方法都是和类型相关的,在使用泛型通配符?时,不能调用。

Collection<?> a可以和任意参数化的类型匹配,但到底匹配的是什么类型,只有以后才知道,所以,

a=new ArrayList<Integer>();和 a= new ArrayList<String>();都可以,但a.add(new Date);或者 a.add("abc");都不行。

 

Cols<Object>中的Object只是说明Cols<Object>实例对象中的方法接收的参数是Object

Cols<Object>是一种具体类型,new HashSet<Date>也是一种具体类型,两者没有兼容性。

 

 

 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!