How to use generic methods in Java?

The usage method of Java generic methods is as follows:

  1. Add angle brackets <> before the return type of the method, and specify the generic parameter inside the angle brackets, for example:
  2. Use generic parameters in the method’s parameter list, for example: T parameter.
  3. Generic parameters can be used within the method body for type checking or conversion operations.

Here is a simple example code:

public class GenericMethodExample {
    // 泛型方法
    public static <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};
        printArray(intArray);

        String[] stringArray = {"Hello", "World"};
        printArray(stringArray);
    }
}

In the above code, we defined a generic method printArray that accepts an array as a parameter and iterates through the array using the generic parameter T to print its elements. In the main method, we called the printArray method separately to print an Integer array and a String array. Since the parameter type of a generic method is determined based on the actual input parameter type, we can call the same generic method in different places and pass in different types of parameters.

bannerAds