the first < U >
is declared, indicating that this type parameter is unique to this method, and the latter U
indicates that the method return type is U
.
< hr >
it is recommended that the subject read more related basic books. The following screenshots are taken from the 10th edition of core java I
.
the first < U > cannot be deleted. If deleted, the compiler will assume that your method returns a class named U (U.class) and will not be found.
this < U > is used to tell the compiler that I'm going to return a generic type here, never mind that I
second update:
The declaration of
< T >
is in this class. Do you think the declaration of this class is:
public Something <T> {
///
}
something like this.
you directly use U
to identify the return value, and JVM will look for the type U.class
, but obviously it doesn't exist, so use < U >
to identify the actual type for the virtual machine to wait until the method is run and then look at the actual type corresponding to U
. Here is the issue of generic erasure of Java . You can check out some articles on your own.
< hr >
Update:
generics can be understood as "allow any type of parameter to be accepted here", but the general usage is for types that require multiple parameters, and generic parameter types have certain associations.
for example, after using generics in a picture, identity
must be of the same type as one of the two input parameters of accumulator
and its return value, and the parameter types accepted by combiner
must also be the same as identity
.
eg.
when identity
is a String
, then the first parameter and return value of accumulator
must be of type String
, otherwise an error will be reported.
this is the expressive power that cannot be achieved when Object
is used to express "allow any type of parameter to be accepted here".
< hr >
Baidu "generic Parameter Type" for more details.