What is the difference between <?> and <T> in java generics?

public static void printColl(ArrayList<?> al){
                Iterator<?> it = al.iterator();
                while(it.hasNext())
                {
                        System.out.println(it.next().toString());
                }
? and T both represent indeterminate types, but if it is T, the function can operate on T. For example,
T t = it.next();
System.out.println(t);

T custom generics and ? wildcard generics
1. Generics are only used in one place in the entire class. When using generics, pay attention to adding parameters. You cannot call methods related to parameter types, such as "+", such as printing out any Anything in a parameterized type collection is suitable for wildcard generics <?>
public static void printCollection(Collection <?> collection)
{
for(Object obj: collection)
{
System.out.println(obj);
}
}
2 . When a type is used to express the relationship between two parameters or between the parameters and the return value, that is, the unified type variables are used in two places in the method signature, or the type variables are also used in the method body code. Not only used when signing, this is where custom generic <T> should be used. Generic parties can call methods of some time types. For example, the add method of a collection.
public static <T> T autoConvertType(T obj)
{
     return(T)obj;
}

Three generic types:
          [1]ArrayList<T> al=new ArrayList<T>(); The specified collection element can only be of type T
          [2]ArrayList<?> al=new ArrayList<?>(); The collection element can be It is an arbitrary type, which is meaningless. It is generally in the method, just to illustrate the usage
          [3]ArrayList<? extends E> al=new ArrayList<? extends E>();
            Generic limitation:
               ? extends E: receives E Type or a subtype of E.
               ? super E: Receives type E or super type of E.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326228970&siteId=291194637
Recommended