Source of generics
In Java, generics are introduced by referencing the template functions of C + +.
intAddintXinty) { returnX +y;}floatAddfloatX.floaty) { returnX +y;}DoubleAddDoubleXDoubley) { returnX +y;}//The abstract and implementation of the integer, floating-point number above the generic functiontemplate<classT>t Add (t x,t y) {returnX +y;}
Public classMygeneric { Public Static voidMain (string[] args) {//general principles for generic inference to return the intersection in a generic parameter, and the generic parameter must be a reference type//3 Auto-boxing integer 5 auto-boxing integer so infer an integerInteger RESULT1 = Add (3, 5); //3.5 Auto-boxing Double 5 auto-boxing integer so infer common parent-class numberNumber RESULT2 = Add (3.5, 5); //3 Auto-boxing integer str1 String common intersection, all objectObject RESULT3 = Add (3, "str1")); } /*** Definition of a generic method: * The angle brackets for the type parameter that is used to place the generic should appear after all other modifiers of the method and before the return type of the method, that is, immediately before the return value, the following <T> * By convention, type parameters are typically used with a single Uppercase letters indicate that * only reference types will be treated as parameters of the square method, and will automatically be boxed.@paramx *@paramy *@return */ Public Static<T>t Add (t x,t y) {//here the compiler will error: the operator + is undefined for the argument type (s) T, T//because not all generics support + operations, but this method can see the Java type inference//T result = x + y; return NULL; }}
Java Foundation _ Custom Generics