黑马程序员-体验泛型

 
/**
*@Package:laladin.learn
*@Project:javaLearn
*@Title:GenericTest.java
*@Description:TODO
*@author Topdog topdog@163.com
*@date 2011-7-10上午09:17:22
*@version v1.0
*/
package laladin.learn;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

/**
 * @ClassName:GenericTest
 * @Description TODO
 * @date 2011-7-10
 */
public class GenericTest {

	/**
	 * @throws Exception 
	 * @Title:main
	 * @Description:TODO
	 * @Param:@param args
	 * @Return:void
	 * @throws
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		ArrayList collection1=new ArrayList();

		collection1.add(1);

		collection1.add(1L);

		collection1.add("abc");

		
//		int i=(Integer)collection1.get(1);//编译要强制类型转换且运行时出错!

		ArrayList<String> collection2=new ArrayList<String>();

		//collection2.add(1);

		//collection2.add(1L);

		collection2.add("abc");

		String element=collection2.get(0);//不需要再进行强制类型转换

		
		ArrayList<Integer> collection3=new ArrayList<Integer>();
		//在编译前,通过泛型限定了类型为Integer,但当编译完成后,将会去掉类型的信息
		System.out.println(collection3.getClass()==collection2.getClass());
		//因此上一句代码将返回True,说明他们实际就是一份字节码。
		
		//collection3.add("abc");
		//下面通过反射穿透泛型,为collection3添加字符串
		collection3.getClass().getMethod("add", Object.class).invoke(collection3, "abc");
		System.out.println(collection3.get(0));
	}

}


参数化类型可以引用一个原始类型的对象,编译报告警告

Collection<String> c=new Vector();

原始类型可以引用一个参数化类型对像,编译报告警告

Collection c=new Vector<String>();

参数化类型不考虑类型参数的继承关系

Vector<String> v =new Vector<Object>(); //错误

Vector<Object> v=new Vector<String>();//错误

在创建数组实例时,数组的元素不能使用参数化类型,例如,下面语句有错误

Vector<Integer> vectorList[]=new Vector<Integer>[10];

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值