java 泛型类型限定

来源:互联网 发布:linux命令大全 chm 编辑:程序博客网 时间:2024/05/16 15:25
import java.util.ArrayList;import java.util.Iterator;public class GenericDemo {public static void main(String[] args) {//method1();method2();}public static void method2() {ArrayList<Student> al = new ArrayList<Student>();al.add(new Student("stu01"));al.add(new Student("stu02"));al.add(new Student("stu03"));/* * printColl_3(al); 错误的相当于传的时 * ArrayList<People> al = new ArrayList<Student>(); * 这种方式你已经定义了只能装People,可以后来又定义 * 只能装Student,传Person的其它子类就会产生冲突 *  */printColl_4(al);}/* * <? extends People> * 泛型限定!!!!这样是上限 * 这样能使用People对象的特有方法 * 既可以接收People也可以接受People的子类 * <? super People> * 这是下限,可以接收People和他的父类 * 使用People的特有方法时要强转 *  */public static void printColl_4(ArrayList<? extends People> al) {Iterator<? extends People> it = al.iterator();while(it.hasNext()) {System.out.println(it.next().getName());}}public static void printColl_3(ArrayList<People> al) {Iterator<People> it = al.iterator();while(it.hasNext()) {System.out.println(it.next().getName());}}public static void method1() {ArrayList<String> al1 = new ArrayList<String>();al1.add("abc");al1.add("def");al1.add("jhi");ArrayList<Integer> al2 = new ArrayList<Integer>();al2.add(1);al2.add(2);al2.add(3);//printColl(al1);//printColl(al2);printColl_2(al1);printColl_2(al2);}public static void printColl(ArrayList<?> al) {Iterator<?> it = al.iterator();while(it.hasNext()) {/* * <?>表示占位符,不明确具体类型, * 不能给it.next()指定具体的返回值类型 * 就是不强转不能给it.next()指定传入的类型 */System.out.println(it.next());}}public static <E> void printColl_2(ArrayList<E> al) {Iterator<E> it = al.iterator();while(it.hasNext()) {/* * 这个静态方法泛型,传入什么类型 * 就是什么类型,可以使用 * E e = it.next(); * 明确it.next()的返回值类型 */E e = it.next();System.out.println(e);}}}class People {private String name;People(String name) {this.name = name;}public String getName() {return name;}}class Student extends People {Student(String name) {super(name);}}

0 0