import java.util.*;
/*
? 通配符。也可以理解为占位符。
泛型的限定;
? extends E: 可以接收E类型或者E的子类型。上限。
? super E: 可以接收E类型或者E的父类型。下限
*/
class GenericDemo6
{
public static void main(String[] args)
{
ArrayList<Person> al = new ArrayList<Person>();//集合al泛型为Person,存Person对象
al.add(new Person("abc1"));
al.add(new Person("abc2"));
al.add(new Person("abc3"));
printColl(al);//打印集合
ArrayList<Student> al1 = new ArrayList<Student>();集合al泛型为Student,存Student对象
al1.add(new Student("abc--1"));
al1.add(new Student("abc--2"));
al1.add(new Student("abc--3"));
printColl(al1); //打印集合,Student是Person的子类
ArrayList<Worker> al2 = new ArrayList<Worker>();//集合al泛型为Worker,存Worker对象
al2.add(new Worker("wabc--1"));
al2.add(new Worker("wabc--2"));
al2.add(new Worker("wabc--3"));
printColl(al2); //打印集合,Worker是Person的子类
}
public static void printColl(Collection<? extends Person> al)//用来打印集合的函数,传递的参数类型是集合型,集合的泛型是Person类及其子类
{
Iterator<? extends Person> it = al.iterator();
while(it.hasNext())
{
System.out.println(it.next().getName());
}
}
}
class Person
{
private String name;
Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
}
class Worker extends Person
{
Worker(String name)
{
super(name);
}
}
|
|