JDK introduces the generic mechanism. The nature of generics is parameterized, that is, the operated data type is specified as a parameter. This type of parameter can be used to create classes, interfaces, and methods, which are called generic classes, generic interfaces, and generic methods.
Typical usage of generic methods:
public static <T> void sort(List<T> list, Comparator<? super T> c)
This is the generic method. If you do not have the <t> definition, an error is returned when you use generics in subsequent parameters.
Basic usage:
public static <M> List<M> findAll(Class<M> m)
If you need to specify the generic type
public static <M extends Model> List<M> findAll(Class<M> m)
Generally, when writing a Java generic method, the return value type and at least one parameter type should be generic, and the type should be consistent. If only the return value type or one of the parameter types uses the generic type, the usage of this generic method is greatly limited, basically to the same level as that of the non-generic method.
#1. For example, the returned value does not use generics:
public static <M> boolean save(M m)
public static <M extends Model> boolean save(M m)
In this case, do not use generic methods. Write them as follows:
public static boolean save(Object m)
public static boolean save(Model m)
#2 For example, parameters do not use generics
In this case, I don't know how to write.
(The following statements are incorrect.) (a wildcard is defined without the generic method)
Public static <m> List <m> findall (class <?> M)
Public static <m> List <m> findall (class <? Extends model> m)
Public static <m> List <m> findall (class <? Super Model> m)
Compilation is successful, but the parameters and return values are of different types. (Potential errors may easily cause runtime exceptions)
By the way;
"?" Unknown type
The extends keyword declares the upper bound of the type, indicating that the parameter type may be the specified type or a subclass of this type.
The super keyword declares the lower bound of the type, indicating that the type of the parameter may be the specified type, or the parent type of this type, until the object
Therefore, using the generic method, the type of the returned value and at least one parameter type should be generic, and the type should be consistent. To specify the return value type through the parameter type.
If your understanding is incorrect, please point it out.