A generic method is similar to a generic class in that it defines a generic as a method, and the format is presumably:
Public < Type parameters > return type method name (generic type variable name) {...}
The generic method is also divided into dynamic methods and static methods:
1. Dynamic generic methods I've actually used it in the previous blog post,
1 Public classBox<t> {2 3 PrivateT obj;4 5 PublicBox () {}6 7 PublicT getobj () {8 returnobj;9 }Ten One public void setobj (T obj) {A. obj = obj; - } - the PublicBox (T obj) { - Super(); - This. obj =obj; - } + -}
The Setobj () is a generic method that uses only the generic parameters provided in the class. We can also define our own generic parameters for a generic method:
1 Public class Box<t> {23/ *... */ 4 5 Public void print (q q) {6 System.out.println (q); 7 }89 }
Note: Generic parameters are defined before the return value type.
This allows us to specify its own generics when the method is called:
1 New Box<>(); 2 b.<string>print ("Hello"); 3 // // Compile error
2. Static generic methods must specify their own type parameters when used, because static methods are loaded as the class loads. When a static method is loaded, there is no instance object for the class, so the type parameters provided by the class cannot be used:
1 public class Box<t> 2 3 ...< /span>*/ 4 5 public static <Q> print (q q) { 6 System.out.println (q);
7 " 8 9 }
It is used in a similar way to dynamic methods.
3. Note : When calling a generic method that has its own type parameter specified, it is not necessary to explicitly specify its generic, and Java can infer the type of the generic at compile-time, such as:
Dynamic:
1 b.print ("Hello");
Static:
1 box.print ("Hello");
Because the incoming type is obviously a string, it is no longer specified.
Java Generic Learning notes-(iii) Generic methods