Generic methods use type parameters to specify the data types that can be operated. The type parameter syntax is
Generic method type parameter specification
In Java, generic methods allow developers to create methods that can be used on multiple types Method of operation. When defining a generic method, we need to specify the type parameters. Type parameters determine the type of data a method can operate on.
Type parameter syntax
Type parameters are specified within angle brackets :
<T> void myMethod(T value) { // 代码主体 }
In this example, < T>
is a type parameter, which indicates that the method can operate on any type of object.
Specify type parameters
Type parameters can be specified by explicitly specifying the type:
<String> void myMethod(String value) { // 操作 String 类型的数据 }
You can also use wildcards to specify type parameters:
?
: Unbounded wildcard, indicating that the type parameter can be of any type. ? extends T
: upper bound wildcard, indicating that the type parameter must be of type T or its subclass. ? super T
: lower bound wildcard, indicating that the type parameter must be of type T or its superclass. Practical case
Suppose we have a List
, which contains various types of objects. We want to write a method to print each element in the list:
import java.util.List; public class Example { public static void main(String[] args) { List<Object> myList = List.of("Hello", 10, true); printElements(myList); } public static <T> void printElements(List<T> list) { for (T element : list) { System.out.println(element); } } }
In this example, the printElements
method is generic and it takes the type parameter T
. Therefore, it can print any type of data in the list.
The above is the detailed content of How to specify type parameters of generic methods?. For more information, please follow other related articles on the PHP Chinese website!