JAVA 泛型初步认识
Java1.5增加了泛型的概念。泛型允许你抽象类型,最常见的例子就是容器类型,如集合类的层次。
List myIntList = new LinkedList(); // 1myIntList.add(new Integer(0)); // 2Integer x = (Integer) myIntList.iterator().next(); // 3必须进行类型转换,iterator()只会返回Object类型。
利用泛型修改上面的程序段
List<Integer> myIntList = new LinkedList<Integer>(); // 1’myIntList.add(new Integer(0)); //2’Integer x = myIntList.iterator().next(); // 3’,不必进行类型转换。
下面是java.util包中定义List和Iterator的代码摘要
public interface List<E> {void add(E x);Iterator<E> iterator();}public interface Iterator<E> {E next();boolean hasNext();}List<String> ls = new ArrayList<String>(); //1
List<Object> lo = ls; //2 编译错误
通常,如果Foo是Bar的一个子类型(子类或子接口),G是某种泛型声明,则G<Foo>不一定是G<Bar>的一个子型。
Wildcards通配符
访问一个集合中的所有元素:
老版本:
void printCollection(Collection c) {Iterator i = c.iterator();for (k = 0; k < c.size(); k++) {System.out.println(i.next());}}利用泛型:void printCollection(Collection<Object> c) {for (Object e : c) {System.out.println(e);}}老版本可以接受任何类型的集合类作为参数,但是新版本的类型只能是Collection<Object>。那么所有类型的集合的父类型是什么呢?是Collection<?>。
void printCollection(Collection<?> c) {for (Object e : c) {System.out.println(e);}}Collection<?> c = new ArrayList<String>();
c.add(new Object()); // compile time error
我们不知道c代表的类型,所以不能向它添加对象。不能添加任何东西,唯一例外是null,因为它是每个类型的子类。