Home  >  Article  >  Java  >  Do Java functions support generics? How to achieve?

Do Java functions support generics? How to achieve?

PHPz
PHPzOriginal
2024-04-26 14:42:02457browse

Java functions support generics. Generics can be implemented by using type parameters in the function signature, indicating that the function can handle different types of data.

Java 函数是否支持泛型?如何实现?

#Do Java functions support generics? How to achieve?

Java functions support generics. Generics refer to using type parameters when defining a function, allowing the function to handle different types of data.

How to implement generic functions?

To implement a generic Java function, you can use type parameters in the function signature, for example:

public static <T> void printArray(T[] arr) {
  for (T element : arr) {
    System.out.println(element);
  }
}

In this example, 8742468051c85b06f0a0af9e3e506b5c represents the type parameter, which will be used in the function for the type of array elements.

Practical case

The following is an example of using generic functions to print integer and string arrays:

public class Main {
  public static void main(String[] args) {
    Integer[] intArr = {1, 2, 3};
    String[] strArr = {"Hello", "World", "!"};

    printArray(intArr); // 输出:1 2 3
    printArray(strArr); // 输出:Hello World !
  }
  
  public static <T> void printArray(T[] arr) {
    for (T element : arr) {
      System.out.println(element);
    }
  }
}

In this case,8742468051c85b06f0a0af9e3e506b5c Type parameters allow the printArray function to print arrays of different types in a generic way. This makes the code more flexible and reusable.

The above is the detailed content of Do Java functions support generics? How to achieve?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn