1.1.
usage of generics
parameterized types such as the type parameter T in sample<t> can be used to type the parameters of the constructor, the type of the return value of the method, the type of the parameter that paints the method, the type of the property field, and so on.
Public classGenericparametertest {//parameterized type T, which can be a reference type such as String,integer. Static classSample<t> { PublicSample (T obj) { This. obj =obj;} //the type of the parameterized type as the return value. PublicT work () {System.out.println ("Work:" + This. obj);return This. obj;} //the parameterized type as the type of the parameter. Public voidupdate (T obj) { This. obj =obj;} //the parameterized type as the type of the property. PrivateT obj;} Public Static voidMain (string[] args) {//correct usage. T is a string. Sample<String> Sample =NewSample<string> ("Hello"); String obj=sample.work (); Sample.update ("World"); obj=sample.work (); System.out.println (obj); //syntax error. Error usage. //sample<int> anothersample = new sample<int> (1);//correct usage. T is an integer.Sample<Integer> anothersample =NewSample<integer> (1); }
The results of the operation are as follows:
Work:hello
Work:world
World
Java Important Technology (19) How to use generics generic type