-什么是泛型Java泛型(generics)是JDK5引入的新特性,泛型提供了一种编译时类型安全检测机制,允许程序员在编译时检测到非法类型。简单理解就是:泛型在编译时指定类型,减少对象类型不匹配导致的运行时异常。它的主要目的是提高我们代码的重用率。我们Java标准库中的ArrayList就是一个典型的泛型应用:publicclassArrayListextendsAbstractListimplementsList,RandomAccess,Cloneable,java.io.Serializable{...publicArrayList(Collectionc){elementData=c.toArray();if((size=elementData.length)!=??0){//c.toArray可能(错误地)不返回Object[](see6260652)if(elementData.getClass()!=Object[].class)elementData=Arrays.copyOf(elementData,size,Object[].class);}else{//replacewithemptyarray.this.elementData=EMPTY_ELEMENTDATA;}}publicvoidsort(Comparatorc){finalintexpectedModCount=modCount;Arrays.sort((E[])elementData,0,size,c);if(modCount!=expectedModCount){thrownewConcurrentModificationException();}modCount++;}.....publicEget(intindex){rangeCheck(index);returnelementData(index);}publicbooleanadd(Ee){ensureCapacityInternal(size+1);//IncrementsmodCount!!elementData[size++]=e;returntrue;}}在源码中,ArrayList中的E称为类型参数变量,而整个ArrayList我们称它们为泛型类型。我们可以指定除基本类型之外的任何类型,例如:ArrayList。在源代码的集合中?通配符类型表示类型的上界,表示参数化的类型可能是T或者T的子类。源码中的Comparator表示类型的下界(在JavaCore中称为supertypelimitation),表示参数化的类型type是这个类型的超类型(supertype),直到Object。两个extends和super通配符在定义泛型类型Generic时,也可以使用extends通配符来限制T的类型:publicclassGeneric{...}现在,我们只能定义:Genericp1=null;通用<整数>p2=newGeneric<>(1,2);通用<双精度>p3=null;因为Number、Integer和Double都符合。非数字类型将无法编译:Genericp1=null;//compileerror!Generic