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

How to define generic methods in Java functions?

WBOY
Release: 2024-05-01 12:39:01
Original
980 people have browsed it

Generic method definition: Specify type parameters () before the method name to achieve common operations across multiple data types. Practical case: The printList method takes the generic 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) {
    // 方法体
}
Copy after login

In this method,

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

Output

Hello
World
1
2
3
Copy after login

In this example, the

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

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