java Generic <T> <?>

A. The difference

T represents a single type, and Class <T> represent this class corresponding to the type, Class <? > Class represents the type of uncertainty

Copy the code
Copy the code
E - Element (used in the collection, since the collection is stored in the element) 
 T - the Type (the Java classes) 
 K - Key (key) 
 V - the Value (Value) 
 N - Number The (Value Type) 
 -? Indefinite represented java type 

illustrate: 
the Set <T> T represents the collection is an instance of the class 
List <E> represents the collection is an instance of the class E 
<?> List represents a collection of objects in the type of uncertainty, not specified 
<?> List List is the same the same. 

Generic role: 
1, with the generic: 
the Java collection Code Code 
List <T> = new new the ArrayList List <T> ();   
T = T List.get (0);   

2, no generic: 
the Java collection Code Code 
List the ArrayList = new new List ();   
T = T (T) List.get (0);
Copy the code
Copy the code

 

Second, how to create an instance of a Class <T> type?

      As with non-generic code, you have two ways: calling the method Class.forName () or using the class constants X.class. Class.forName () is defined as a return to Class <?>. On the other hand, the class is defined as having constant X.class type Class <X>, it is String.class Class <String> type.

Third, why the method requires <T> T modifying it

Generic statement must be after the modifier methods (public, static, final, abstract, etc.), before returning a value statement.

public static <T> T request2Bean(HttpServletRequest request,Class<T> clazz){}

Wherein the first <T> is the argument passed Class <T> corresponding to a generic equivalent to the return value, the return value is the latter type T, representative of the method must return T type (that incoming class <T> determined)

Guess you like

Origin www.cnblogs.com/daijiabao/p/11583053.html