How do you define generic methods in Java?
In Java, the syntax for defining generic methods is to add a type parameter before the return value of the method, and then use this type parameter in the method’s parameter list. An example is shown below:
public class GenericMethodExample {
// 定义一个泛型方法,使用类型参数T
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
// 创建一个整数数组
Integer[] intArray = {1, 2, 3, 4, 5};
// 创建一个字符串数组
String[] stringArray = {"Hello", "World"};
// 创建GenericMethodExample对象
GenericMethodExample example = new GenericMethodExample();
// 调用泛型方法printArray,并传入整数数组
example.printArray(intArray);
// 调用泛型方法printArray,并传入字符串数组
example.printArray(stringArray);
}
}
In the example above, the printArray method is defined with a type parameter T that can represent any type. By using generic methods, we can use this type parameter within the method. In the main method, we create an array of integers and an array of strings, and print the elements of the arrays by calling the printArray method. Regardless of whether an integer array or a string array is passed in, the printArray method can correctly print the elements of the array.