java泛型的两种用法:List是泛型方法,List
public interface Dao{
List<T> getList(){};
}
List<String> getStringList(){
return dao.getList();//dao是一个实现类实例
}
List<Integer> getIntList(){
return dao.getList();
}
上面接口的getList方法如果定义成List
List<T> getList<T param1,T param2>
这样可以限制返回结果的类型以及两个参数的类型一致。
List
public Class Fruit(){}
public Class Apple extends Fruit(){}
public void test(? extends Fruit){};
test(new Fruit());
test(new Apple());
test(new String()); //这个就会报错
这样可以现在test方法的参数必须是Fruit或其子类。
类型参数“”和无界通配符“
public class ArrayList<E> extends AbstractList<E> implements List<E>,RandomAccess,Cloneable,java.o.Serializable{
......
}
ArrayList中的“E”也是类型参数。只是表示容器中元素Element的时候,习惯用“E”。换一个简单的例子,我们自己定义一个新泛型容器叫Box。
class Box<T>{
private T item1;
private T item2;
}
为什么这里要用类型参数?因为这是一种”约束“,为了保证Box里的item1, item2都是同一个类型T。Box,代表两个item都是String。Box里两个item都是Integer。
List容器库里都帮我们写好了,所以我们是不会去定义List的。
那什么时候会出现List?有几种情况,要么是作为泛型类的成员字段或成员方法的参数间接出现。还是刚才Box的例子:
class Box<T>{
private List<T> item;
public List<T> get(){return item;}
public void set(List<T> t){item=t;}
}
现在Box类里有三个地方出现了List:
成员字段item的类型
get( )方法的返回值
set( )方法的参数
这里写成List为了表示和Box类型参数保持一致。
2. 声明泛型方法
另外一种会出现List的地方是泛型方法。比如Function类的reduce是个静态泛型方法,负责对列表里的所有元素求和。这里的List出现在参数,函数返回值和函数内部,也是为了保持泛型类型的一致性。
class Fuction{
public static <T> List<T> reduce(List<T> list){
//...do something
}
}
- 无界通配符
class Box<?>{
private ? item1;
private ? item2;
}
所以通配符是拿来使用定义好的泛型的。比如声明List容器的一个实例对象。
List<?> list = new ArrayList<String>();
List<?> list = new ArrayList<String>();
list.add("hello"); //ERROR
list.add(111); //ERROR
//argument mismatch; String cannot be converted to CAP#1
//argument mismatch; int cannot be converted to CAP#1
另外如果拿List
class Box<T>{
private List<T> item;
public List<T> get(){return item;}
public void set(List<T> t){item=t;}
//把item取出来,再放回去
public void getSet(Box<?> box){box.set(box.get());} //ERROR
}
新的getSet()方法,只是把item先用get()方法读出来,然后再用set()方法存回去。按理说不可能有问题。实际运行却会报错。
error: incompatible types: Object cannot be converted to CAP#1
原因和前面一样,通配符box
class Box<T>{
private List<T> item;
public List<T> get(){return item;}
public void set(List<T> t){item=t;}
//helper()函数辅助getSet()方法存取元素
public void getSet(Box<?> box){helper(box);}
public <V> void helper(Box<V> box){box.set(box.get());}
}
- 有界通配符