Home  >  Article  >  Java  >  How to specify type parameters of generic methods?

How to specify type parameters of generic methods?

PHPz
PHPzOriginal
2024-05-03 11:54:02673browse

Generic methods use type parameters to specify the data types that can be operated. The type parameter syntax is , which can be specified by explicitly specifying the type or using wildcards, such as: ? (unbounded), ? extends T (upper bound) and ? super T (lower bound). Wildcards specify the scope of a type parameter, for example, ? extends T means that the type parameter must be of type T or a subclass thereof.

How to specify type parameters of generic methods?

Generic method type parameter specification

In Java, generic methods allow developers to create methods that can be used on multiple types Method of operation. When defining a generic method, we need to specify the type parameters. Type parameters determine the type of data a method can operate on.

Type parameter syntax

Type parameters are specified within angle brackets :

<T> void myMethod(T value) {
    // 代码主体
}

In this example, is a type parameter, which indicates that the method can operate on any type of object.

Specify type parameters

Type parameters can be specified by explicitly specifying the type:

<String> void myMethod(String value) {
    // 操作 String 类型的数据
}

You can also use wildcards to specify type parameters:

  • ?: Unbounded wildcard, indicating that the type parameter can be of any type.
  • ? extends T: upper bound wildcard, indicating that the type parameter must be of type T or its subclass.
  • ? super T: lower bound wildcard, indicating that the type parameter must be of type T or its superclass.

Practical case

Suppose we have a List, which contains various types of objects. We want to write a method to print each element in the list:

import java.util.List;

public class Example {

    public static void main(String[] args) {
        List<Object> myList = List.of("Hello", 10, true);
        printElements(myList);
    }

    public static <T> void printElements(List<T> list) {
        for (T element : list) {
            System.out.println(element);
        }
    }
}

In this example, the printElements method is generic and it takes the type parameter T . Therefore, it can print any type of data in the list.

The above is the detailed content of How to specify type parameters of generic methods?. 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