泛型——类型通配符

来源:互联网 发布:法律家法律数据库 编辑:程序博客网 时间:2024/06/05 07:16
通过一个例子来逐步说明通配符的使用。

假设有一个需求:定义一个方法可以迭代给定的List集合,被迭代的集合通过参数传入。

尝试1:不使用泛型形参

public static void iteratorList(List list){Iterator it = list.iterator();while(it.hasNext()){System.out.println(it.next());}}

List集合是带有泛型参数的,如果没有加泛型参数有可能出现泛型警告,所以考虑给上面的List集合加上泛型实参。但是泛型实参是什么类型呢??
因为List集合中可以存储任何类型的元素,所以考虑使用Object。

尝试2:使用Object作为泛型实参

修改后的iteratorList方法如下:

public static void iteratorList(List<Object> list){Iterator it = list.iterator();while(it.hasNext()){System.out.println(it.next());}}

修改后的代码肯定不会出现泛型警告了,但在调用时却出现了问题,看如下代码:

public static void main(String[] args){List<Date> dateList = new ArrayList<>();List<String> strList = new ArrayList<>();List<Integer> intList = new ArrayList<>();List<Double> doubleList = new ArrayList<>();iteratorList(dateList);iteratorList(strList);iteratorList(intList);iteratorList(doubleList);}

编译失败:

error: incompatible types: List<Date> cannot be converted to List<Object>    iteratorList(dateList);                 ^error: incompatible types: List<String> cannot be converted to List<Object>    iteratorList(strList);                 ^error: incompatible types: List<Integer> cannot be converted to List<Object>    iteratorList(intList);                 ^error: incompatible types: List<Double> cannot be converted to List<Object>    iteratorList(doubleList);                 ^

这是因为,虽然Object是Date、String、Integer、Double的父类,但是 List<Object> 不是 List<Date>、List<String>、List<Integer>、List<Double> 的父类,因而不能把 List<Date> 等类型的对象赋给 List<Object> 类型的变量。

尝试3:使用类型通配符

那怎么做才能既消除泛型警告,又能迭代所有的List集合呢??使用类型通配符。如下代码所示:

public static void iteratorList(List<?> list){Iterator it = list.iterator();while(it.hasNext()){System.out.println(it.next());}}

设定类型通配符的上限

假设我们又有一个需求,定义一个方法,可以迭代List集合,但集合的元素只能是Number及其子类,集合通过参数传入。
直接上代码吧。

public static void iteratorList(List<? extends Number> list){Iterator it = list.iterator();while(it.hasNext()){System.out.println(it.next());}}

注意:

使用类型通配符时,只能从集合中取元素,不能向集合中添加元素,否则编译失败。如下代码所示:

public static void iteratorList(List<?> list){list.add("1");}

编译失败:

error: no suitable method found for add(String)                list.add("1");                    ^    method Collection.add(CAP#1) is not applicable      (argument mismatch; String cannot be converted to CAP#1)    method List.add(CAP#1) is not applicable      (argument mismatch; String cannot be converted to CAP#1)  where CAP#1 is a fresh type-variable:    CAP#1 extends Object from capture of ?


0 0
原创粉丝点击