java 泛型类型限定

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值