package demo.assemble;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class 泛型限定 {
public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<>();
al.add(new Student("a", 18));
al.add(new Student("b", 15));
ArrayList<Teacher> al2 = new ArrayList<Teacher>();
al2.add(new Teacher("a", 18));
al2.add(new Teacher("b", 15));
//迭代并打印集合
printCollection(al);
printCollection(al2);
}
//迭代并打印集合
private static void printCollection(Collection<?> al) {//?通配任意类型 相当于? extends Object
System.out.println("打印:");
Iterator<?> it = al.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
//泛型上限 ? extends E 存元素用上限
private static void printCollection2(Collection<? extends Person> al) {//只能使用Person子类型或者Person类
System.out.println("打印:");
Iterator<? extends Person> it = al.iterator();
while (it.hasNext()) {
Person p = it.next();//父类引用指向子类对象
System.out.println(p);
}
}
//泛型下限 ? super E 取元素用下限
private static void printCollection3(Collection<? super Person> al) {//只能使用Person父类型的或者Person类
System.out.println("打印:");
Iterator<? super Person> it = al.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
泛型限定:泛型上限 ? extends E泛型下限 ? super E
最新推荐文章于 2023-02-17 16:00:44 发布
本文探讨了Java中的泛型限定,展示了如何使用泛型上限和下限进行集合操作。通过示例代码,解释了如何创建ArrayList并添加不同类型对象,以及如何使用迭代器打印集合内容。同时,详细解析了`printCollection`方法,该方法接受不同类型的集合参数,分别展示了`? extends Person`(泛型上限)和`? super Person`(泛型下限)的用法。
1941

被折叠的 条评论
为什么被折叠?



