java 泛型 通配符 上边界 下边界理解的几个例子1

/**
 * 泛型  ? 通配符  理解
 * 		? 可以引用任何类型
 * 		? 可以使用与参数化 无关的方法
 * 
 * 上边界  ? extends Number  包括自己
 * 
 * 下边界  ? super  Integer  包括自己
 * 
 */
public class GenericTest2 {

	public static void main(String[] args) throws Exception {
		
		ArrayList<String> collection2 = new ArrayList<String>();
		collection2.add("abc");
		collection2.add("efg");
		
		//ArrayList type of Integer
		ArrayList<Integer> collection3 = new ArrayList<Integer>();
		collection3.add(1);
		collection3.add(2);
		
		printCollection(collection2);
		printCollection(collection3);
		
		Class<?>  x1 = String.class.asSubclass(Number.class);
		Class<?>  x2 = Class.forName("java.lang.String");
	}
	
	public static void printCollection(Collection<?> collection) {
		System.out.println(collection.size());
		for(Object obj :collection) {
			System.out.println(obj);
		}
		
		collection = new HashSet<String>();
		collection = new HashSet<Integer>();
	}
	
	/**
	 * 这个方法不可行
	 * ArrayList<String> = Collection<Object>  编译器不允许你这么玩
	 * 两边的参数类型 必须一致
	 * @param collection
	 */
	public static void printCollection1(Collection<Object> collection) {
		
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值