Home > Java > javaTutorial > body text

Do Java functions support generics? How to achieve?

PHPz
Release: 2024-04-26 14:42:02
Original
481 people have browsed it

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);
  }
}
Copy after login

In this example, <T> 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);
    }
  }
}
Copy after login

In this case,<T> 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!