/**
*@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];