泛型12·第21章3383940I/ Create resultmatrix41E result-42(E[])new Number[matrix].1ength][matrix2[0].length];4344// Perform multiplication of two matrices45for (int 1=O; i<result.length; i++)t46for (int j.-O;j<result[o].length;j++)47result[i][j]=zeroO;48for(intk=0;k<matrixl[0].length;k++)4950resu]t[i][j]add(result[i][j],51multipiy(matrixl[i][k],matrix2[k][j]));52}53)54力5556return result;575859/Print matrices,the operator,and their operation result */60public static void printResult(61Number[[]ml,Number[m2,Number[[]m3,charop)62for(int=o:i<ml.length;i++)t63for (int j=o;j<ml[oj.length:j++)64System.out.print(""+mi[ij[jj);6566if (iml.length/ 2)67"+op+";System.out.print("68else");69System.out.print("7071for (int j-O;j<m2.length;j++)72System.out.print(""+m2[ij[j]);7374if(im1.length/2)75");System.out.print("=76else*);77System.out.print("7879for(intj=O;j<m3.length;j++)80System.out.print(m3[i][jj+""");8182System.out.printlnO;83了843851程序清单21.10实现了IntegerMatrix类。该类在第1行扩展了GenericMatrix<Integer>。在泛型实例化之后,GenericMatrix<Integer>中的add方法就成为Integeradd(Integero1,Integero2)。该程序实现了Integer对象的add、multiply和zero方法。因为这些方法只能被addMatrix和multiplyMatrix方法调用,所以,它们仍然是protected的。南程序清单21.10IntegerMatrix.javapub1ic class IntegerMatrix extends GenericMatrix<Integer>12/eImplementtheaddmethodforadding twomatrixelementsPDG-3protected Integer add(Integer ol,Integer o2) (4return 01 +02;567/Implement the multiply method for multiplying two8matrix elements */
型·13第21章重泛protected Integer multiply(Integer ol, Integer o2)(910return 01 02;11子12/ Implement the zero method to specify zero for Integer*/1314protected Integer zeroOf15return O;16子17)程序清单21.11实现了RationalMatrix类。Rational类在14.13节中介绍过。Rational是Number的子类型。RationalMatrix类在第1行扩展了GenericMatrix<Rational>。在泛型实例化之后,ladd(Rational o1,Rationalo2).GenericMatrix<Rational>中的add方法就成为Rational该程序实现了Rational对象的add、multiply和zero方法。因为这些方法只能被addMatrix和multiplyMatrix方法调用,所以,它们仍然是protected的。程序清单21.11RationalMatrix.java1publicclass RationalMatrixextends GenericMatrix<Rational>f2/*Implement theaddmethod foraddingtwo rational elements]3protected Rational add(Rational rl,Rational r2) f4return r1.add(r2);56子7/** Implement the multiply method for multiplying8two rational elements */9protected Rational muitiply(Rational r1,Rational r2)10return r1.mu1tiply(r2);1131213/s Implementthe zeromethod to specify zero for Rational/14protected Rational zeroOf15return new Rational(0,l):16317 J程序清单21.12给出了一个程序,该程序创建两个Integer矩阵(第4~5行)和一个IntegerMatrix然后在第12行和第16行对这两个矩阵进行相加和相乘操作。对象(第8行),程序清单21.12TestIntegerMatrix.java1pub1icclass TestIntegerMatrixN.public static void main(String) args)3//Create Integer arraysml,m24IntegermlnewInteger[f(1,22,3),(4,5,6),{1,1,13);nInteger门m2-newInteger((1,1,1),(2,2,2)00,03;67I// Create an instance of IntegerMatrix89IntegerMatrix integerMatrix -new IntegerMatrixO;茶10System.out.println("Inml+m2is");11GenericMatrix.printResult(X12ml,m2,integerMatrix.addMatrix(ml,m2),+');茶1314System.out.printin("Inml*m2is");15GenericMatrix.printResult(16ml,m2,integerMatrix.multiplyMatrix(ml,m2),"e'):HPDG1718)
型14·第21章泛品m1+m2is111234123456222678+111000111ism1.m2555123111*456222141414=00031113二个程序,该程序创建两个Rationa1矩阵(第4~10行)和二个程序清单21.13给出了(第13行),RationalMatrix对象然后在第17行和第21行对这两个矩阵进行相加和相乘操作。程序清单21.13TestRationalMatrix.java1pub1icclass TestRationalMatrix(2pubiic static void main(String) args)(3// Create two Rational arrays ml and m24Rational[]] ml=new Rational[3][3];5Rationa1[]]m2newRational[3][3];6for (int 1=;i <ml.length; i++)7for(int j-o;j<mi[o].length;j++){8ml[i][jj-newRationai(i+1,j+5);9m2[i][j]newRational(i +1,j+6)1011112//CreateaninstanceofRationalMatrix13RationalMatrix rationalMatrix =new RationalMatrixO:1415System.out.println("nml+m2 is");16GenericMatrix.printResult(17ml,m2,rationalMatrix.addMatrix(ml,m2),'+');1819System.out.println("Inml*m2 is");20GenericMatrix.printResult(21ml,m2,rationalMatrix.multiplyMatrix(ml,m2),*):22123ml+m2is品1/51/61/71/61/71/811/3013/4215/562/51/32/71/32/71/411/1513/2115/28+1/23/73/83/51/23/711/1013/1445/56mlm2is1/51/61/71/61/71/8101/630101/735101/840t2/51/32/71/32/71/4101/315202/735101/420-3/51/23/71/23/73/8101/210101/245101/280关键术语actualconcretetype(实际具体类型)unboundedwildcord(<?>)(非受限通配)boundedgenerictype(受限泛型类型)boundedwildcard(<?extendsE>)(受限通配)formalgenerictype(形式泛型类型)lowerboundwildcard(<?superE>)(下限通配)PDGgenericinstantiation(泛型实例化)rawtype(原始类型)本章小结·泛型是指参数化类型的能力。使用泛型能定义带泛型类型的类或方法,之后编译器会用具体类型
型·15第21章泛来替换泛型类型。·泛型的主要优势是能够在编译时而不是运行时发现错误。·泛型类或方法允许指定对象允许的类型,以和这个类或方法一起工作。如果试图使用带有不兼容对象的类或方法,编译器会检测出这个错误。·定义在类、接口或者静态方法中的泛型称为形式泛型类型,随后可以用一个实际具体类型来替换它。替换泛型类型的过程称为泛型实例化。·不使用类型参数的泛型类称为原始类型,例如ArrayList。使用原始类型是为了向后兼容JDK较早的版本。·通配泛型类型有三种形式:?,?extendsT或者?superT,这里的T代表一个泛型类型。第种形式“?"称为非受限通配,它和?extendsobject是一样的。第二种形式?extendsT称为受限通配,代表T或者T的一个未知子类型。第三种类型?superT称为下限通配,表示T或者T的一个未知父类型。·使用称为类型消除的方法来实现泛型。编译器使用泛型类型信息来编译代码,但是随后消除它。因此,泛型信息在运行时是不可用的。这个方法能够使泛型代码向后兼容使用原始类型的遗留代码。·不能使用泛型类型参数来创建实例。·不能使用泛型类型参数来创建数组·不能在静态环境中使用类的泛型类型参数。·在异常类中不能使用泛型类型参数。复习题21.2~21.4节21.1图a和图b中有编译错误吗?ArrayList dates= new ArrayListO:ArrayList<Date> datesdates.add(newDateO):newArrayList<Date>Odates.add(newDateO);dates.add(newStringO);dates.add(new StringO):b)a)21.2图a中有什么错误?图b中的代码正确吗?ArrayList dates-new ArrayListO;ArrayList<Date>dates-dates.add(newDate(O);newArrayList<Date>O;dates.add(new DateO):Date date - dates.get(o):Date date dates.get(o);b)a)21.3使用泛型类型的优势是什么?21.4为iava.lang.Comparable编写泛型声明。21.5如果使用new,ArrayList<String>()创建了字符串的ArrayList的一个实例,那么应该将ArrayList类的构造方法定义为如下所示吗?久public ArrayList<E>()A21.6泛型类可以拥有多个泛型参数吗?21.7在类中如何定义一个泛型类型?在方法中如何声明一个泛型类型?PDG21.8什么是受限泛型类型?21.5~21.6节21.9什么是原始类型?GenericStack与GenericStack<Object>一样吗?21.10什么是非受限通配?受限通配?下限通配?
16·第21章泛型21.11如果将程序清单21.8中的第12~13行改为如下所示,会发生什么情况?pub1ic static <T> void add(GenericStack<T> stackl,GenericStack<T>stack2)21.12如果将程序清单21.8中的第12~13行改为如下所示,会发生什么情况?public static <T>void add(GenericStack<? extends T> stackl,GenericStack<T>stack2)21.7节21.13什么是消除?为什么使用消除来实现Java泛型?21.14如果你的程序使用了ArrayList<list>和ArrayList<Date>,JVM会加载它们吗?21.15可以使用newE()为泛型类型E创建一个实例吗?为什么?21.16使用泛型类作为参数的方法可以是静态的吗?为什么?21.17可以定义一个自定制的泛型异常类吗?为什么?编程练习题21.1(修改程序清单21.1)修改程序清单21.1中的GenericStack类,使用数组而不是ArrayList来实现它。你应该在给栈添加新元素之前检查数组的大小。如果数组满了,就创建一个新数组,该数组是当前数组大小的两倍,然后将当前数组的元素复制到新数组中。21.2(泛型二分查找法)使用二分查找法实现下面的方法。pub1icstatic<Eextends Comparable<E>>intbinarySearch(EJ1ist,Ekey)21.3(泛型选择排序)使用选择排序法实现下面的方法。pub1ic static<Eextends Comparable<E>>void selectionSort(E[) 1ist)21.4(泛型插入排序法)使用插入排序法实现下面的方法。pub1ic static<EextendsComparable<E>>voidinsertionSort(E[]1ist)21.5(数组中的最大元素)实现下面的方法,返回数组中的最大元素。pub1ic static <E extends Comparable<E>> Emax(E[J1ist)21.6(二维数组中的最大元素)编写一个泛型方法,返回二维数组中的最大元素public static<E extendsComparable<E>>Emax(E[J[] 1ist)福放和寳PDG