|
public static void Printcoll (Arraylist<?> al) {
Iterator<?> it = Al.iterator ();
while (It.hasnext ())
{
System.out.println (It.next (). toString ());
}
? and T both represent the type of uncertainty, but if it is T, then the function can operate on t, such as while it can be written like this
T t = It.next ();
System.out.println (t);
T custom generics and? Wildcard generics
1. There is only one place in the entire class that uses generics, and when used, it is noted that the parameter cannot invoke methods related to parameter types such as "+", such as printing out all the contents of any parameterized type set, and is suitable for wildcard generics <?>
public static void Printcollecton (Collection <?> Collection)
{
for (Object obj:collection)
{
System.out.println (obj);
}
}
2. When a type face is used to express the relationship between the two parameters or the parameter and the return value, that is, the uniform types of variables are used in two places of the method signature, or the type variables are used in the method body code, not only when the signature is used, which should be used with custom generics <T>. A generic party can invoke methods of some time type. For example, the Add method of a collection.
public static <T> t Autoconverttype (t obj)
{
return (t) obj;
}
|
Three types of generics:
[1] Arraylist<t> al=new arraylist<t> (); Specifies that the collection element can only be of type T
[2] Arraylist<?> al=new arraylist<?> (); A collection element can be any type, which is meaningless, usually in a method, just to illustrate usage
[3] arraylist<? Extends e> al=new arraylist<? Extends E> ();
Limitations of generics:
? Extends e: Receives subtype of e type or E.
? Super E: Receives the type E or the parent of E. |
The above describes the Java generics and what is the difference? , including the aspects of the content, want to be interested in other programming tutorials friends helpful.
What is the difference between <?> and <T> in Java generics?