Generic methods
Generic method definition rules:
- All generic method declarations have a part of a type parameter declaration (delimited by angle brackets) that is part of the type parameter declaration before the method return type.
- Each type parameter declaration section contains one or more type parameters, separated by commas between the parameters. A generic parameter, also known as a type variable, is the identifier used to specify a generic type name.
- A type parameter can be used to declare a placeholder for the actual parameter type that returns a value type and can be obtained as a generic method.
- The declaration of a generic method body is the same as other methods. Note that the type parameter can only represent a reference type, not the original type (like Int,double,char, and so on)
Examples of generic methods:
public <T> T GP (T t) {return t;} Public void GP2 (T t) {System.out.println (t);} Public Boolean GP3 (T t,e E) {return t.equals (e);}
Generic class
Generic class-Definition rules:
- Add the type parameter declaration section after the class name, and the type parameter declaration part of the generic class also contains one or more type parameters, separated by commas
Generic class Examples:
Public classMain { Public Static voidMain (string[] args) {GP<String> gp=NewGp<string>(); Gp.sett ("GP"); System.out.println (Gp.equals ("GP")); }}classGp<t>{ PrivateT T; Public voidsett (t t) { This. t=T; } Public Booleantt (T t1) {returnt.equals (t1); }}
You can use it as a list.
Type wildcard character
- Type wildcard characters are generally used ? Instead of a specific type parameter. For example, list<?> is logically a parent class for all list< concrete type arguments >, such as list<string>,list<integer>.
Maximum wildcard characters <, extends t>
- <? Extends t> indicates that the wildcard represents a subclass of type T and T. For example:List<? extends number >
Low limit of wildcard characters <? Super T>
- <? Super t> indicates that the wildcard represents a type that is the parent class of T and T types. For example:List<? Super number >
Rookie Tutorial: Http://www.runoob.com/java/java-generics.html
Java generic methods, generic classes, wildcard characters, wildcard upper and lower bounds