泛型的通配符:? 未知类型
泛型的限定 ? extends Person
package generic.advance.Demo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import p2.bean.Person;
import p2.bean.Students;
import p2.bean.Worker;
public class GenericAdvanceDemo2 {
public static void main(String[] args) {
ArrayList<Worker> al=new ArrayList<Worker>();
al.add(new Worker("abc",30));
al.add(new Worker("abc4",34));
ArrayList<Students> al2=new ArrayList<Students>();
al2.add(new Students("stu",20));
al2.add(new Students("stu3",23));
printCollection(al);
printCollection(al2);
}
/**
* 迭代并打印集合中的元素
*
* 可以对类型进行限定:
* ?extends E:可以接受E类型的或者E的子类型的对象。上限
*
* ?super E:可以接受E类型或者E的父类型。下限
一般在储存元素的时候都用上限 因为这样取出都是按照上限类型来运算的。不会出现类型安全隐患
通常在对集合中的元素进行取出操作时 可以使用下限(例如 比较器)
* @param al
*/
/* public static void printCollection(Collection<? extends Person> al) {
Iterator<? extends Person> it=al.iterator();
while(it.hasNext()) {
Person p=it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}
*/
public static void printCollection(Collection<? super Students> al) {
Iterator<? super Students> it=al.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}