1. Why is there a generic type?
(1) The early object type can receive arbitrary types of objects, but in actual use, there will be type conversion problems, there is also a hidden danger, so Java provides generics to solve this security problem .
2. Use of generic classes:
(1) First define a generic class Objecttool, as follows:
1 Packagecn.itcast_04;2 3 /*4 * Generic class: Define Generics on class5 */6 Public classObjecttool<t> {7 PrivateT obj;8 9 PublicT getobj () {Ten returnobj; One } A - Public voidsetobj (T obj) { - This. obj =obj; the } -}
(2) write a test for a generic class:
1 Packagecn.itcast_04;2 3 /*4 * Testing of generic classes5 */6 Public classObjecttooldemo {7 Public Static voidMain (string[] args) {8 //objecttool ot = new Objecttool ();9 //Ten //ot.setobj (New String ("Wind Qing")); One //string s = (string) ot.getobj (); A //System.out.println ("name is:" + s); - // - //ot.setobj (new Integer); the //integer i = (integer) ot.getobj (); - //System.out.println ("Age is:" + i); - - //ot.setobj (New String ("Brigitte")); + // //classcastexception - //Integer II = (integer) ot.getobj (); + //System.out.println ("name is:" + II); A atSystem.out.println ("-------------"); - -objecttool<string> ot =NewObjecttool<string>(); - //ot.setobj (new Integer);//This is the time to compile . -Ot.setobj (NewString ("Brigitte")); -String s =ot.getobj (); inSystem.out.println ("name is:" +s); - toObjecttool<integer> Ot2 =NewObjecttool<integer>(); + //ot2.setobj (New String ("Wind Qing"));//This is the time to compile . -Ot2.setobj (NewInteger (27)); theInteger i =ot2.getobj (); *System.out.println ("Age is:" +i); $ }Panax Notoginseng}
The results of the operation are as follows:
A collection framework for the reinforcement of Java Fundamentals Note 31: Overview and basic use of generic classes for collections