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

One, T custom generics and? Wildcard generics

? And T both represent uncertain types  

public static void printColl(ArrayList<?> al){
    Iterator<?> it = al.iterator();
    while(it.hasNext()){
        System.out.println(it.next().toString());
    }
}

But if it is a custom generic T, T can be manipulated in the function. For example, it can be written like this in while

T t = it.next();
System.out.println(t);

1. Wildcard generic type <?> Applicable scenarios:

Only one place in the whole class uses generics. When using it, pay attention to adding generic parameters to not call methods related to parameter types .

For example, to print out all the content in any parameterized type set, it is suitable to use wildcard generic <?>
 

public static void printCollecton(Collection <?> collection){
    for(Object obj: collection){
        System.out.println(obj);
    }
}

2. Customize the generic <T> to adapt to the scene:

When a type variable is used to express the relationship between two parameters or between a parameter and a return value, that is, unified variables of various types are used in two places (parameters or return values) of the method signature, or the type variable is used in the method body code It is also used instead of only when signing, which should use custom generic <T>.

The generic party can call some methods about the type. For example, the add method of the collection.
 

public static <T> T autoConvertType(T obj){
     return(T)obj;
}

 

There are 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 It is an arbitrary type, this kind of meaningless, generally in the method, just to illustrate the usage
          [3]ArrayList<? extends E> al=new ArrayList<? extends E>();
          The limit of generic type
               :? Extends E: receive E Type or subtype of E.
               ? super E: Receive E type or E's super type.

Guess you like

Origin blog.csdn.net/sanmi8276/article/details/108616223
Recommended