Generic method definition: Specify type parameters (
Definition of generic methods in Java functions
##Generic methodsallow us to Use type parameters to create generic methods that can work on multiple data types.
Define a generic method
To define a generic method, place the generic type parameter list in front of the method name and enclose it in parentheses. Parentheses enclose it. For example:public <T> void printElement(T element) { // 方法体 }
is a type parameter, which means that the method can accept and operate elements of any type
T.
Practical Case
Consider the following scenario where each element in a list of different types needs to be printed:Code Example
public static <T> void printList(List<T> list) { for (T element : list) { System.out.println(element); } } public static void main(String[] args) { List<String> stringList = List.of("Hello", "World"); List<Integer> integerList = List.of(1, 2, 3); printList(stringList); printList(integerList); }
Output
Hello World 1 2 3
printList method is generic because it accepts type parameters
. This makes it possible to print a list of elements of any type without having to create separate methods for each type.
The above is the detailed content of How to define generic methods in Java functions?. For more information, please follow other related articles on the PHP Chinese website!