Home  >  Article  >  Java  >  How to define generic methods in Java functions?

How to define generic methods in Java functions?

WBOY
WBOYOriginal
2024-05-01 12:39:01864browse

Generic method definition: Specify type parameters (8742468051c85b06f0a0af9e3e506b5c) before the method name to achieve common operations across multiple data types. Practical case: The printList method takes the generic 8742468051c85b06f0a0af9e3e506b5c to accept lists of different types as parameters and prints elements one by one without creating a separate method for each type.

Java 函数中泛型方法如何定义?

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) {
    // 方法体
}

In this method,

8742468051c85b06f0a0af9e3e506b5c 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

In this example, the

printList method is generic because it accepts type parameters8742468051c85b06f0a0af9e3e506b5c. 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!

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