Home > Java > javaTutorial > Generic methods and generic classes for Java function generics

Generic methods and generic classes for Java function generics

PHPz
Release: 2024-04-25 18:15:02
Original
424 people have browsed it

Java generics include generic methods and generic classes. Generic methods allow the use of a single method to handle different types of data, the type of which is parameterized by the method (for example, List getElements(List list)); generic classes allow the creation of general classes that can be used with different data types (e.g., List getElements(List list)) For example, class MyGenericClass { private T value; }).

Java 函数泛型的泛型方法和泛型类

Generic methods and generic classes of Java function generics

Generic methods

Generic methods allow you to create methods in which the type is parameterized rather than explicitly specified as a specific data type. This way you can use one method to handle different types of data without having to write a different method for each data type.

public static <T> List<T> getElements(List<T> list) {
    // 在此处操作列表元素
    return list;
}
Copy after login

In this method, T is a type variable, indicating that the method can handle any type of data.

Practical case:

List<Integer> intList = getElements(List.of(1, 2, 3));
List<String> stringList = getElements(List.of("a", "b", "c"));
Copy after login

Generic classes

Generic classes allow you to create classes whose data types are not Fixed, but specified by the parameterized type. This allows you to create generic classes that can be used with different data types.

public class MyGenericClass<T> {
    private T value;

    public MyGenericClass(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}
Copy after login

In this class, T is a type variable, indicating that this class can handle any type of data.

Practical case:

MyGenericClass<Integer> intClass = new MyGenericClass<>(10);
MyGenericClass<String> stringClass = new MyGenericClass<>("Hello");
Copy after login

The above is the detailed content of Generic methods and generic classes for Java function generics. For more information, please follow other related articles on the PHP Chinese website!

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