小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
Java泛型(Generic)是J2 SE1.5中引入的一个新特性,其本质是参数化类型,也就是说所操作的数据类型 被指定为一个参数(type parameter)这种参数类型可以用在类、接口和方法的创建中,分别称为泛型 类、泛型接口、泛型方法。
官方说明: When you take an element out of a Collection , you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time. Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.
参照:docs.oracle.com/javase/1.5.…
官网查找路径: www.oracle.com/cn/java/tec…
jdk程序员指南-5.0英文版:docs.oracle.com/javase/1.5.…
New Features and Enhancements:docs.oracle.com/javase/1.5.…
generics Generics:docs.oracle.com/javase/1.5.…
为什么要使用泛型程序设计
泛型程序设计(Generic programming)意味着编写的代码可以被很多不同类型的对象所重用。 存在问题 编译期间没有代码检查 调用期间发现转换异常。
下面的程序描述的是JDK5没有泛型对象重用的问题。
使用泛型前
pulic class ArrayList{
private int size = 0;
private object[] elements = {};
public Object get(int i){
if(size > i){
return elements[i];
}
throw new IndexOutOfBoundsException();
}
pulic void add(Object o){
size++;
Object[] array = new Object[size];
for(int i = 0 ;i<elements.length;i++){
array[i] = elements[i];
}
array[size-1]=0;
elements = array;
}
public static void main(string[] args){
ArrayList arrayList = new ArrayList();
arrayList.add(1);
arrayList.add('a');
arrayList.add(new File("/"));//1
String file = (String) arrayList.get(2);//2
}
}
对于程序中描述的第一处这里没有错误检查。可以向数组列表中添加任何类的对象。对于第二处,对于这个调用,编译和运行都不会出错。然而在其他地方,如果将get的结果强制类型转换为 String类型,就会产生一个错误。
使用泛型后
public class ArrayListNew<E>{
private int size = 0;
private object[] elements = {};
public Object get(int i){
if(size > i){
return elements[i];
}
throw new IndexOutOfBoundsException();
}
public void add(E o){
size++;
Object[] array = new Object[size];
for(int i=0;i<elements.length;i++){
array[i]=elements[i];
}
array[size-1]=0;
elements = array;
}
public static void main(String[] args) {
ArrayListNew<String> arrayList = new ArrayListNew<String>();
arrayList.add('a');
String s = (String) arrayList.get(0);
}
}